【问题标题】:Send image with Retrofit2使用 Retrofit2 发送图像
【发布时间】:2017-01-17 20:42:17
【问题描述】:

我正在尝试使用 Retrofit2 将图像上传到服务器,但我非常不确定如何执行此操作。

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

这是我目前正在使用的代码 sn-p,它不会向服务器发送任何内容:

// 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);

但是,我可以使用带有 TypedFile 的 Retrofit 1.9 来做到这一点。

是我做错了什么还是 Retrofit2 对这类事情有问题?

【问题讨论】:

标签: android retrofit2


【解决方案1】:

我已经为此苦苦挣扎了一段时间,我最终找到了这个解决方案以使其最终发挥作用......希望它有所帮助:

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);

【讨论】:

    【解决方案2】:

    您好,请检查我们如何在改造 2 中发送图像。在部分形式中,您还需要发送图像和其他数据。

    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();
        }
    });
    

    谢谢,希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-07
      • 1970-01-01
      • 2021-11-06
      • 2023-03-16
      • 2019-06-23
      相关资源
      最近更新 更多