【问题标题】:How to Upload a photo using Retrofit?如何使用 Retrofit 上传照片?
【发布时间】:2016-04-12 16:59:30
【问题描述】:

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

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

这是我发送请求的代码:

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 一直告诉我照片不是文件并且编码类型有问题。 谁能帮我解决这个问题?

【问题讨论】:

    标签: android retrofit multipartform-data


    【解决方案1】:

    尝试使用@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);
    ...
    

    编辑:

    您也可以查看我的answer 来回答一个非常相似的问题。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

        • 如果图片很大,这个会失败
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-14
        • 1970-01-01
        • 2014-12-10
        相关资源
        最近更新 更多