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

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

自定义Headers

创建业务请求接口

public interface Api {

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

}

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

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());
        }
    });
}
上一篇 Retrofit2学习之五:自定义请求头
下一篇 Retrofit2学习之七:上传多个文件
目录
文章列表
1 PHP下划线和驼峰字符串相互转换
PHP下划线和驼峰字符串相互转换
2
设计模式(14)迭代器模式
设计模式(14)迭代器模式
3
Groovy代码示例 - map
Groovy代码示例 - map
4
TinkerPatch基本使用步骤
TinkerPatch基本使用步骤
5
Gitlab目录层级超过6级报500错误不能显示文件列表的问题解决
Gitlab目录层级超过6级报500错误不能显示文件列表的问题解决
最新评论
一位WordPress评论者
一位WordPress评论者
2月12日
您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。