如何使用翻新功能上传照片? [英] How to Upload a photo using Retrofit?

查看:84
本文介绍了如何使用翻新功能上传照片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Android应用程序中使用Retrofit与REST-API通信. 当用户在我的应用程序中更改其个人资料图片时,我需要发送请求并上传新图像.这是我的服务:

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);

但是当我将此请求发送到服务器时,REST一直告诉我照片不是文件,并且编码类型出了点问题. 有人可以帮我解决这个问题吗?

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?

推荐答案

尝试使用@Body代替@Part.

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

然后使用MultipartBuilder来构建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);
...

您也可以检查我的答案以解决非常相似的问题.

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

这篇关于如何使用翻新功能上传照片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆