android retrofit2 如何多文件上传

android retrofit2 文件上传

1、build.gradle中添加依赖

compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
compile 'com.google.code.gson:gson:2.5'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

2、需实现的API接口类

public interface FileUpload {
    /**
     * 单文件上传
     * @param description
     * @param file @Part MultipartBody.Part file 使用MultipartBody.Part类发送文件file到服务器
     * @return 状态信息String
     */
    @Multipart
    @POST("UploadServerAddr")
    Call> uploadFile(@Part("description") RequestBody description, @Part MultipartBody.Part file);

    /**
     * 多文件上传:通过 List 传入多个part实现
     * @param parts 每一个part代表一个文件
     * @return 状态信息String
     */
    @Multipart
    @POST("UploadServerAddr")
    Call> uploadFilesMultipartBodyParts(@Part() List parts);

    /**
     * 通过 MultipartBody和@body作为参数来实现多文件上传
     * @param multipartBody MultipartBody包含多个Part
     * @return 状态信息String
     */
    @POST("UploadServerAddr")
    Call uploadFilesMultipartBody(@Body MultipartBody multipartBody);
}

3、 创建OkHttpClient、Retrofit对象

public static final String BASE_URL = "http://×××/UploadFileServer/"; 

//Log应用拦截器                
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

//创建OkHttpClient对象
OkHttpClient client = new OkHttpClient.Builder()
      .addInterceptor(interceptor)  //okHttp的Log应用拦截器
      .retryOnConnectionFailure(true)
      .connectTimeout(15, TimeUnit.SECONDS)
      .build();

//创建Retrofit               
Retrofit retrofit = new Retrofit.Builder() 
      .client(client) //设置OKHttpClient   
      .baseUrl(BASE_URL)  //设置baseUrl, baseUrl必须后缀"/"
      .addConverterFactory(GsonConverterFactory.create())  //添加Gson转换器
      .build();

4、获取、调用FileUpload的API函数实现单个文件或多文件上传

FileUpload fileUpload = retrofit.create(FileUpload.class); //获取FileUpload的API

// 上传单一文件
String des = "a image";
RequestBody description = RequestBody.create( MediaType.parse("multipart/form-data"), des);

RequestBody requestFile = RequestBody.create(MediaType.parse("text/plain"), new File("/sdcard/0/test.jpg"));
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);

Call call = fileUpload.uploadFile(description, body);
call.enqueue(new Callback() {
     @Override
     public void onResponse(Call call, Response response) {
     }

     @Override
     public void onFailure(Call> call, Throwable t) {
     }
});

// 上传多文件,参数:List parts对象
ArrayList list = new ArrayList();
list.add(new File("/sdcard/0/test0.jpg"));
list.add(new File("/sdcard/0/test1.jpg"));

List parts = new ArrayList<>(list.size());
for(File file : list) {
    RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
    MultipartBody.Part part = MultipartBody.Part.createFormData("image", file.getName(), requestBody);
    parts.add(part);
}

Call call = fileUpload.uploadFilesMultipartBodyParts(parts);
call.enqueue(new Callback() {
     @Override
     public void onResponse(Call call, Response response) {
     }

     @Override
     public void onFailure(Call> call, Throwable t) {
     }
});

// 上传多文件,参数:MultipartBody对象
ArrayList list = new ArrayList();
list.add(new File("/sdcard/0/test0.jpg"));
list.add(new File("/sdcard/0/test1.jpg"));

MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
for(File file : list) {
     RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
     builder.addFormDataPart("image", file.getName(), requestBody);
}
MultipartBody multipartBody = builder.build(); //List parts = builder.build().parts();

Call call = fileUpload.uploadFilesMultipartBody(multipartBody);
call.enqueue(new Callback() {
     @Override
     public void onResponse(Call call, Response response) {
     }

     @Override
     public void onFailure(Call> call, Throwable t) {
     }
});
 

你可能感兴趣的:(Android)