如何在 Retrofit 2 中上传图像文件

问题描述:

我有一张像下面这样的邮递员图片.如何在 Retrofit 2 中做同样的事情?

I have an image of postman like below. How can I do the same thing in Retrofit 2?

我已经声明了这样的接口:

I've declared the interface like this:

@Multipart
@POST("/api/Pharmarcy/UploadImage")
Call<ResponseBody> uploadPrescriptionImage(
        @Query("accessToken") String token,
        @Query("pharmarcyRequestId") int pharmacyRequestedId,
        @Part MultipartBody.Part image);

@Multipart
@POST("user/updateprofile")
Observable<ResponseBody> updateProfile(@Part("user_id") RequestBody id,
                                       @Part("full_name") RequestBody fullName,
                                       @Part MultipartBody.Part image,
                                       @Part("other") RequestBody other);

//pass it like this
File file = new File("/storage/emulated/0/Download/Corrections 6.jpg");
RequestBody requestFile =
        RequestBody.create(MediaType.parse("multipart/form-data"), file);

// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
        MultipartBody.Part.createFormData("image", file.getName(), requestFile);

// add another part within the multipart request
RequestBody fullName = 
        RequestBody.create(MediaType.parse("multipart/form-data"), "Your Name");

service.updateProfile(id, fullName, body, other);

看看我传递多部分和字符串参数的方式.希望能帮到你!

Look at the way I am passing the multipart and string params. Hope this will help you!