android端:
String fileName = tvFilename.getText().toString();
RequestBody description =
RequestBody.create(
okhttp3.MultipartBody.FORM, fileName);
File fileImage = new File(saveFileName);
RequestBody requestBody1 =
RequestBody.create(MediaType.parse("multipart/form-data"), fileImage);
MultipartBody.Part body =
MultipartBody.Part.createFormData("bannerImage", fileImage.getName(), requestBody1);
RestClient.api().addLive(description, body)
.enqueue(new retrofit2.Callback() {
@Override
public void onResponse(retrofit2.Call call, retrofit2.Response response) {
"处理成功"
}
@Override
public void onFailure(retrofit2.Call call, Throwable t) {
"处理失败"
}
});
@Multipart
@POST("add/live")
Call<ResponseInfo> addLive(
@Part("fileName")RequestBody fileName,//其他字段
@Part MultipartBody.Part bannerImage);//图片
服务器端:
@RequestMapping(value = "/add/live", method = RequestMethod.POST)
@ResponseBody
public ResponseInfo addLive(
@RequestParam(value = "fileName") String fileName,
@RequestParam(value = "bannerImage") MultipartFile bannerImage
)throws Exception {
String logoPath = "/logo/score/";
try {
File file = new File(imagePath + logoPath);
FileUtils.writeByteArrayToFile(file, bannerImage.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
return new ResponseInfo(T1TConstants.SUCCESS, "成功");
}
参考:http://blog.csdn.net/bluejww/article/details/52856213
https://medium.com/@adinugroho/upload-image-from-android-app-using-retrofit-2-ae6f922b184c#.pghubpxxk