简体   繁体   中英

How to Upload a photo using Retrofit?

I'm using Retrofit in my Android application to communicate with a REST-API. When user changes his profile picture in my application, I need to send a request and upload new image. This is my service:

 @Multipart
 @PATCH("/api/users/{username}/")
 Call<User> changeUserPhoto(@Header("Authorization") String token,@Path("username") String userName , @Part("photo") RequestBody photo);

And this is my code to send request:

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(GlobalVars.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        UserService userService = retrofit.create(UserService.class);
        Callback<User> callback = new Callback<User>() {
            @Override
            public void onResponse(Response<User> response, Retrofit retrofit) {

                if (response.isSuccess()) {
                    //do sth
                } else {
                   // do sth else
                }
            }


            @Override
            public void onFailure(Throwable t) {
                t.printStackTrace();
            }
        };
        RequestBody photo = RequestBody.create(MediaType.parse("application/image"), new File(imageUir));
        Call<User> call = userService.changeUserPhoto(token, username, photo);

        call.enqueue(callback);

But when I send this request to server, REST keeps telling me that photo is not a file and something is wrong with encoding type. Can anybody help me how to fix this?

Try using @Body instead of @Part .

@PATCH("/api/users/{username}/")
Call<User> changeUserPhoto(@Header("Authorization") String token,@Path("username") String userName , @Body RequestBody photo);

then use MultipartBuilder to build the RequestBody

RequestBody photo = RequestBody.create(MediaType.parse("application/image"), file);
RequestBody body = new MultipartBuilder()
        .type(MultipartBuilder.FORM)
        .addFormDataPart("photo", file.getName(), photo)
        .build();

Call<User> call = userService.changeUserPhoto(token, username, body);
...

EDIT:

You can also check my answer to a very similar question.

更好的选择是将位图转换为字符串并上传为字符串。

将您的照片转换为base64并将其作为简单的字符串体上传。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM