使用 Retrofit2 发送图像

Send image with Retrofit2

我正在尝试使用 Retrofit2 将图像上传到服务器,但我不确定如何上传。

文档让我有点困惑,我尝试了提到的解决方案 ,但它对我不起作用。

这是我当前使用的代码片段,它不会向服务器发送任何内容:

// 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界面中:

@Multipart
@POST(Constants.URL_UPLOAD)
Observable<Response<ResponseBody>> uploadNew(@PartMap Map<String, RequestBody> params);

您好,请检查我们如何以 retrofit2.In 形式发送图像,您还需要发送图像和其他数据。

public interface ApiInterface {
    @Multipart
    @POST("0.1/gallery/{galleryId}/addImage/")
    Call<User> checkapi (@Part("file\"; filename=\"pp.png\" ") RequestBody file , @Part("FirstName") RequestBody fname, @Part("Id") RequestBody id);
}

File file = new File(imageUri.getPath());
RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), firstNameField.getText().toString());
RequestBody id = RequestBody.create(MediaType.parse("text/plain"), AZUtils.getUserId(this));
Call<User> call = client.editUser(AZUtils.getToken(this), fbody, name, id);
call.enqueue(new Callback<User>() {
    @Override
    public void onResponse(retrofit.Response<User> response, Retrofit retrofit) {
        AZUtils.printObject(response.body());
    }

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
});

谢谢希望这对你有帮助。