用retrofit上传文件时,可以采用如下的两种方式
方式一:
Retrofit的接口,ApiServer.java
@Multipart
@POST("{your_http_server}/user/attr/upload/")
Observable<BaseResponse> uploadImg(@Part("userId") RequestBody userId, @Part("type") RequestBody type, @Part MultipartBody.Part body);
调用方式
// 图片文件
File file = new File("{file_path}");
// 获取图片类型
int index = file.getName().lastIndexOf(".");
String fileType = file.getName().substring(index + 1);
if (fileType.equals("jpg")) {
fileType = "jpeg";
}
// 创建图片的Part
RequestBody reqFile = RequestBody.create(MediaType.parse("image/" + fileType), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("part", file.getName(), reqFile);
// 创建userId和type的Part,都是String类型
RequestBody typeBody = RequestBody.create(MediaType.parse("text/plain"), "profile");
RequestBody userIdBody = RequestBody.create(MediaType.parse("text/plain"), AndroidApplication.getInstance().getAppUser().getUserId());
// 调用接口
Retrofit.create(ApiServer.class).uploadImg(userIdBody, typeBody, body);
方式二:
Retrofit接口文件,ApiServer.java
@Multipart
@POST("{your_http_server}/user/attr/upload/")
Observable<BaseResponse> uploadImage(@PartMap Map<String, RequestBody> map);
调用方式
File file = new File(params.getUri().getPath());
int index = file.getName().lastIndexOf(".");
String fileType = file.getName().substring(index + 1);
if (fileType.equals("jpg")) {
fileType = "jpeg";
}
RequestBody fileBody = RequestBody.create(MediaType.parse("image/"+filetype), file);
RequestBody typeBody = RequestBody.create(MediaType.parse("text/plain"), "profile");
RequestBody userIdBody = RequestBody.create(MediaType.parse("text/plain"), AndroidApplication.getInstance().getAppUser().getUserId());
Map<String, RequestBody> map = new HashMap<String, RequestBody>();
map.put("userId", userIdBody);
map.put("type", typeBody);
map.put("part\"; filename=\"" + file.getName(), fileBody);
Retrofit.create(ApiServer.class).uploadImage(map);