【问题标题】:How to upload just an image using Retrofit 2.0如何使用 Retrofit 2.0 只上传一张图片
【发布时间】:2016-03-24 00:48:40
【问题描述】:

尝试上传图像,但它一直只发送字节,而不是图像文件。这是一个非常简单的调用,除了图像本身,我不需要发送任何参数。我不知道如何格式化日志,所以除非有要求,否则我不会在这里发布错误。

服务:

public interface FileUploadService {

@Multipart
@POST("upload_profile_picture")
Call<ResponseBody> uploadProfilePicture(@Part("profile_picture") RequestBody file);
}

正在调用(之前生成了一个文件,必须删除此代码,因为 SO 需要帖子主要是单词..dumb..):

    // Generate the service from interface
    FileUploadService service = ServiceGenerator.createService(FileUploadService.class, this);

    // Create RequestBody instance from file
    RequestBody requestFile =
            RequestBody.create(MediaType.parse("image/*"), imageFile);
    Log.d(LOG_TAG, "formed file");

    // finally, execute the request
    Call<ResponseBody> call = service.uploadProfilePicture(requestFile);
    Log.d(LOG_TAG, "sending call");
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call,
                               Response<ResponseBody> response) {
            Log.d(LOG_TAG, "success");
            Log.d(LOG_TAG, response.toString());
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.d(LOG_TAG, "failure");
            Log.e(LOG_TAG, t.getMessage());
        }
    });

是 MediaType.parse 方法的问题吗?我也尝试过“multipart/form-data”、“image/jpeg”等,但没有任何效果。

服务器团队说他们正在接收调用,只是作为字节而不是图像文件。

我不断收到 400,因为它正在发送所有字节。我怎么能发送这个?我需要作为多部分发送还是什么?从我所见,您只需要使用@Body 标记方法中的参数并执行上述操作,它应该都可以工作。谁能告诉我为什么会这样?谢谢!

【问题讨论】:

    标签: image file upload retrofit retrofit2


    【解决方案1】:

    这是 Retrofit 2 中的 known issue

    编辑:在最终的 2.0 版本中添加了对 OkHttp 的 MultipartBody.Part 的支持。

    为了让它工作,你需要先改变你的界面:

    @Multipart
    @POST("upload_profile_picture")
    Call<ResponseBody> uploadProfilePicture(@Part MultipartBody.Part file);
    

    然后你必须创建Part 并像这样进行调用:

    MultipartBody.Part file = MultipartBody.Part.createFormData(
                "file",
                imageFile.getName(),
                RequestBody.create(MediaType.parse("image/*"), imageFile));
    
    Call<ResponseBody> call = service.uploadProfilePicture(file);
    

    【讨论】:

      猜你喜欢
      • 2016-04-25
      • 1970-01-01
      • 2013-07-28
      • 2016-11-22
      • 1970-01-01
      • 2019-11-20
      • 1970-01-01
      • 1970-01-01
      • 2017-05-21
      相关资源
      最近更新 更多