How to Upload a photo using Retrofit?

岁酱吖の 提交于 2019-11-28 08:52:34

问题


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?


回答1:


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.




回答2:


The better option would be converting bitmap to string and upload as string.




回答3:


Convert your photo to base64 and upload it as a simple string body.



来源:https://stackoverflow.com/questions/33482385/how-to-upload-a-photo-using-retrofit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!