废话不多说直接上代码:
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接口的地址:, 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 call = photoapi.uploadPhoto(housecode, photos); call.enqueue(new Callback () { @Override public void onResponse(Call call, Response response) { Log.i(TAG, "onResponse:成功 "+response.body().toString()); } @Override public void onFailure(Call call, Throwable t) { } }); }
//房屋多图上传最新的 @Multipart @POST("house/uploadPhoto") Call后台使用java的ssm框架搞的,代码如下:uploadPhoto(@Part("houseCode") String houseCode,@PartMap Map , RequestBody> imgs1);
/**
* 上传文件
*
* @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文件中配置上传的设置:
切记Android中的
photos.put("file\"要和RequestParam中的value的值一样。