您的位置:首页 > 编程语言 > Java开发

使用retrofit上传多张图片和文字,java后台

2017-09-30 16:40 841 查看
废话不多说直接上代码:

Android端代码:

case R.id.save_housephoto://上传图片
new Thread(){
@Override
public void run() {
super.run();
upLoadPhoto();
}
}.start();
break;


具体上传图片的代码:

//上传图片
private void upLoadPhoto() {
if(imagePaths.size()==0){
Toast.makeText(AddpointActivity.this,"请选择图片",Toast.LENGTH_SHORT).show();
return;
}
Map<String, RequestBody> photos = new HashMap<>();
if (imagePaths.size()>0) {
for (int i=0;i<imagePaths.size();i++) {
String substring = imagePaths.get(i).substring(imagePaths.get(i).lastIndexOf("/") + 1, imagePaths.get(i).length());
photos.put("file\"; filename=\""+substring,RequestBody.create(MediaType.parse("multipart/form-data"), new File(imagePaths.get(i))));
}
}
Retrofit retrofit=new Retrofit.Builder()
.baseUrl(Constant.BASEURL)
.addConverterFactory(GsonConverterFactory.create())
.build();
PhotoUploadApi photoapi=  retrofit.create(PhotoUploadApi.class);
Call<JsonResult> call = photoapi.uploadPhoto(housecode, photos);
call.enqueue(new Callback<JsonResult>() {
@Override
public void onResponse(Call<JsonResult> call, Response<JsonResult> response) {
Log.i(TAG, "onResponse:成功 "+response.body().toString());
}
@Override
public void onFailure(Call<JsonResult> call, Throwable t) {

}
});

}

接口的地址:

//房屋多图上传最新的
@Multipart
@POST("house/uploadPhoto")
Call<JsonResult> uploadPhoto(@Part("houseCode") String houseCode,@PartMap Map<String, RequestBody> imgs1);

后台使用java的ssm框架搞的,代码如下:

/**
* 上传文件

* @param session
* @param file
* @return
*
*/

@RequestMapping(value = "/house/uploadPhoto", produces"text/html;charset=UTF-8")
@ResponseBody
public String fileUpload(HttpSession session, 

@RequestParam(value = "file", required = true) MultipartFile[] multiFiles, 

String houseCode) {

for (MultipartFile multipartFile : multiFiles) {

String path = Property.getProperty("fileUpload.path");
File dir = new File(path);
if (!dir.exists()) {
dir.mkdir();
}

String filename = "";
if (!multipartFile .isEmpty()) {
// log.debug(session.getServletContext().getRealPath(path));
try {
// 用UUID而不是时间戳
filename = UUID.randomUUID().toString() + "____" +
multipartFile .getOriginalFilename();

// 文件保存路径
String filePath = path + "/" + filename;
// 转存文件
multipartFile .transferTo(new File(filePath));

} catch (Exception e) {
log.error(CustomStringUtils.getExceptionInfo(e));
return JSONUtil.toJsonString(new JsonResult(-1, "上传发生错误!", null));
}
}

}

return JSONUtil.toJsonString(new JsonResult(1, "上传成功!", null));
}

记得在springMvc.xml文件中配置上传的设置:

    <!-- 上传文件bean -->  

    <bean id="multipartResolver"                    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">   

        <property name="defaultEncoding" value="utf-8" /> 

        <property name="maxUploadSize"   

        value="10485760000" /> <property name="maxInMemorySize" value="40960" />   

    </bean>

切记Android中的

photos.put("file\"

要和RequestParam中的value的值一样。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: