android - 如何在 Android 中使用 retrofit 2 以 JSON 格式上传多部分图像数据?

标签 android json retrofit image-uploading retrofit2

如何将图像文件与我的 json 一起上传。

我的请求 JSON 格式如下。

{
    "Request": {
        "first_name": "Josmy",
        "last_name": "J",
        "profile_image_attributes": {
            "image":"file"
        }
    }
}

在我的 gson 类中,我正在输入类似这样的值

public class Request implements Serializable {
    @SerializedName("first_name")
    private String firstName;
    @SerializedName("last_name")
    private String lastName;
    @SerializedName("profile_image_attributes")
    private MultipartBody.Part profileImageAttributes;
}

@Headers("Content-Type:application/json")
@POST(PSDApiconstants.REGISTRATION)
Observable<PSDSignUpResponseBean> registration(@Body PSDRegistrationRequestBean requestBean);

有没有办法不把请求改成

  {
      "imag": "File",
      "first_name": "Josmy",
      "last_name": "J",
    }

编辑

目前我认为retrofit 2.0.1不支持这种模式下的图片上传。所以我使用 Asynchttp 来解决这个问题。但可能是 retrofit 2 将在 7 月底将其包含在他们的最新版本中

最佳答案

在 retrofit 2.0 中,您可以使用 MultipartBody.Part 上传图像。

声明你的服务

@Multipart
@POST("/api/imageupload")
Observable<Response> uploadImage(@Part MultipartBody.Part imageFile);

创建您的改造客户端对象并调用您的 api。

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(YOUR_API_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

//prepare image file
File file = new File(imagePath);
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part imageFileBody = MultipartBody.Part.createFormData("image", file.getName(), requestBody);

YourAPI service = retrofit.create(YourAPI.class);
Call<Response> call = service.uploadImage(imageFileBody);
call.enqueue(new Callback<Response>() {
    @Override
    public void onResponse(Call<Response> call, Response<Response> response) {
        //handle success
    }

    @Override
    public void onFailure(Call<User> call, Throwable t) {
        //handle error
    }
}

关于android - 如何在 Android 中使用 retrofit 2 以 JSON 格式上传多部分图像数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37785512/

相关文章:

android - Android 2.2.1在音乐开始时崩溃()

Android FFmpeg 日志显示 “File://protocol not found”

android - 如何获取android-comboseekbar-master中选择的步长值

java - Android Retrofit 如何使调用可打包?

android - 网络调用报警超时

android - 如何通过 Retrofit 在 @Query 中传递自定义枚举?

java - 在 list 文件包文件中允许使用任何连字符或字符

javascript - 从屏幕上异步删除 JSON 对象

javascript - 为什么我的数组没有按照我将对象插入数组的方式排序?

json - Safari 内容阻止 Swift 的多个过滤器