Retrofit2学习之六:上传单个文件

Retrofit2 上传需要用到 Multipart,使用 MultipartBody.Part 标识文件体。

自定义Headers

创建业务请求接口

1
2
3
4
5
6
7
8
9
10
11
12
13
public interface Api {

/**
* 上传单个文件
* @param description
* @param file
* @return
*/
@Multipart
@POST("upload")
Call<ResponseBody> uploadFile(@Part("description") RequestBody description, @Part MultipartBody.Part file);

}

创建一个Retrofit的实例,然后利用Retrofit实例创建接口对象和调用接口方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public static final String MULTIPART_FORM_DATA = "multipart/form-data";

@NonNull
private RequestBody prepareFromPart(String description) {
return RequestBody.create(MediaType.parse(MULTIPART_FORM_DATA), description);
}

/**
* 一个域对应一个文件
* @param partName
* @param filePath
* @return
*/
private MultipartBody.Part prepareFilePart(String partName, String filePath) {
File file = new File(filePath);
// 为file建立RequestBody实例
RequestBody requestFile = RequestBody.create(MediaType.parse(MULTIPART_FORM_DATA), file);
// MultipartBody.Part借助文件名完成最终的上传
return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
}

public void uploadFile(View view) {
String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "generated.apk";

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SERVER_ADDRESS)
.build();

api = retrofit.create(Api.class);

// 添加Form的part
RequestBody description = prepareFromPart("hello, this is description speaking");

// 创建文件的part (photo, video, ...)
MultipartBody.Part fileBody = prepareFilePart("file", filePath);

api.uploadFile(description, fileBody).enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//在UI主线程运行
if (response.isSuccessful()) {
Log.i(TAG, "上传成功");
}
}

@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.i(TAG, "上传失败: " + t.getLocalizedMessage());
}
});
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :