OkHttp MultipartBody uploadFile 单张图片和多张上传 详解

api文件编写:
@Multipart
@POST("public/uploadFile/uploadFiles.api")//单张上传图片
Observable> upload(@Part MultipartBody.Part file);
@Multipart
@POST("public/uploadFile/uploadFiles.api")//多张上传图片
Observable> uploads( @Part List  file);
HttpMethods文件编写:
public Observable upload(MultipartBody.Part doc) {
     return Direct.create(demoService.upload(doc));
 }
 public Observable uploads(List  doc) {
     return Direct.create(demoService.uploads(doc));
 }

实践代码模块:

         单个文件上传:

        File file = new File(cropImageUri.getPath());//文件路径
//        //MediaType 有多种类型
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), file);
       //files 上传参数
        MultipartBody.Part part= MultipartBody.Part.createFormData("files", file.getName(), requestBody);

        HttpMethods.getInstance().upload(part).subscribe(new MyObserver() {......}

  多个文件上传:

MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
for (String path : paths) {//List paths多个文件本地路径地址
    Log.d("TAG", path);
    File file = new File(path);
    RequestBody requestBody = RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), file);
    builder.addFormDataPart("files",file.getName(),requestBody);//files 文件上传参数
}
List parts = builder.build().parts();
HttpMethods.getInstance().uploads(parts).subscribe(new MyObserver() {.....}

文件FileUploadRData类是返回数据

/**
 * 返回文件url  外部访问链接
 */
private List fileName;

OK  ,是不是很简单!

 

 

 

你可能感兴趣的:(上传图片)