繁体   English   中英

如何使用Retrofit上传照片?

[英]How to Upload a photo using Retrofit?

我在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一直告诉我照片不是文件,编码类型有问题。 任何人都可以帮我解决这个问题吗?

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

编辑:

您也可以查看我对非常相似问题的答案

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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