如何使用翻新功能上传照片?

编程入门 行业动态 更新时间:2024-10-06 21:36:47
本文介绍了如何使用翻新功能上传照片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在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.

更多推荐

如何使用翻新功能上传照片?

本文发布于:2023-11-26 18:51:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634767.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   上传照片   功能

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!