1、接口范例:
public interface FileUploadService {
//一张图片
@Multipart
@POST("upload")
Call<ResponseBody> upFile(@Part("description") String description,
@Part MultipartBody.Part file);
//多张图片
@Multipart
@POST("oss/androidUpload")
Observable<UpImageResult> upFiles(@Part("description") String description,
@PartMap() Map<String, RequestBody> maps);
}
2、代码示例:
public class FileUploadUtils {
/**
* 一张图片上传
* @param mRepositoryManager
* @param imgPath
* @return
*/
public static Observable<ResponseBody> upImage(Retrofit retrofit , String imgPath){
File file = new File(imgPath);
// 创建 RequestBody,用于封装构建RequestBody
final RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part 和后端约定好Key,这里的partName是用image
MultipartBody.Part body =
MultipartBody.Part.createFormData("file", file.getName(), requestFile);
return retrofit.create(FileUploadService.class).upImage(1,body);
}
/**
* 多张图片上传
* @param mRepositoryManager
* @param imgPath
* @return
*/
public static Observable<ResponseBody> upFiles(Retrofit retrofit , List<String> files) {
Map<String,RequestBody> bodyMap = new HashMap<>();
if (files.size() > 0){
for (int i = 0; i < files.size() ; i++) {
File file = new File(files.get(i));
bodyMap.put("file"+i+"\"; filename=\""+file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file));
}
}
return retrofit.create(FileUploadService.class).upFiles(1,bodyMap);
}
}
网友评论