我正在尝试使用 Retrofit2 将图像上传到服务器,但我不确定如何上传。
文档让我有点困惑,我尝试了提到的解决方案 here ,但它对我不起作用。
这是我目前正在使用的代码 fragment ,它不会向服务器发送任何内容:
// Service
@Multipart
@POST("0.1/gallery/{galleryId}/addImage/")
Call<ResponseBody> addImage(@Path("galleryId") String galleryId, @Part MultipartBody.Part image);
//Call
MultipartBody.Part imagePart = MultipartBody.Part.createFormData("image", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
Call<ResponseBody> call = service. addImage("1234567890", imagePart);
但是,我可以将 Retrofit 1.9 与 TypedFile 一起使用。
是我做错了什么还是 Retrofit2 对这类事情有问题?
最佳答案
我为此苦苦挣扎了一段时间,我最终找到了这个解决方案,最终让它发挥作用......希望它能有所帮助:
Map<String, RequestBody> map = new HashMap<>();
map.put("Id",Utils.toRequestBody("0"));
map.put("Name",Utils.toRequestBody("example"));
String types = path.substring((path.length() - 3), (path.length()));
File file = new File(pathOfYourFile);
RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpg"), file);
map.put("file\"; filename=\"cobalt." + types + "\"", fileBody);
Call<ResponseBody> call = greenServices.upload(map);
在greenServices
接口(interface)中:
@Multipart
@POST(Constants.URL_UPLOAD)
Observable<Response<ResponseBody>> uploadNew(@PartMap Map<String, RequestBody> params);
关于android - 使用 Retrofit2 发送图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39578583/