编辑
记录如何使用retrofit2上传图片
本文访问次数:0

接口声明如下所示

@Multipart
@POST(Api.API_UPLOAD_IMAGE)
Call<ResponseBody> uploadImage(@Query("flag") String flag,@Part MultipartBody.Part image);

图片需要转换成对应的MultipartBody.Part类型

File file = new File(path);
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(path);
if (extension != null) {
    type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
RequestBody requestBody = RequestBody.create(MediaType.parse(type), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestBody);

发起网络请求

Call<ResponseBody> call = client.uploadImage("one", body);
call.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        uploadImageSucceed();
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable throwable) {
        uploadImageFailed();
    }
});

需要输入验证码才能留言

没有任何评论