简体   繁体   English

如何在Android中使用retrofit 2上传JSON中的多部分图像数据?

[英]How to upload multipart image data in JSON with retrofit 2 in android?

How can i upload image file along with my json. 我如何上传图像文件和我的json。

My request JSON looks in the below format. 我的请求JSON以下面的格式查看。

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

In my gson class i am inputting values some what like this 在我的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);

is there any way without changing the request to 有什么办法没有改变请求

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

EDIT 编辑

Currently I think retrofit 2.0.1 dosen't support image upload in this pattern. 目前我认为改造2.0.1不支持这种模式下的图像上传。 so i use Asynchttp to solve this problem. 所以我使用Asynchttp来解决这个问题。 But may be retrofit 2 will include this in their latest release by the end of july 但可能是改造2将在7月底的最新版本中包括这个

In retrofit 2.0 you can upload image using MultipartBody.Part. 在改造2.0中,您可以使用MultipartBody.Part上传图像。

Declare your service 声明你的服务

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

Create your retrofit client object and call your api. 创建您的改造客户端对象并调用您的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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM