Image upload using retrofit2 Put method

醉酒当歌 提交于 2019-12-13 03:16:27

问题


I am new to retrofit2. I want upload image through api service as a file. I have tried with postman by selecting a file and found its working. But through mobile how can I upload the image file.

Here is the Header section of Api

--header 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \

In the body section I am having, "picture", "name", "email" and "phone"

I am trying like,

i have created a class with body parameters UpdateRequest Class

    public class UpdateRequest {
        @SerializedName("picture")
        MultipartBody.Part picture;
        @SerializedName("name")
        public String name;
        @SerializedName("email")
        public String email;
        @SerializedName("phone")
        public String phone;

//Also Generated Getters and Setters for the parameters    

    }

Api Interface function

public interface MediaUploadApiInterface {

    @Headers({
            "content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"
    })
    @PUT("api/employee")
        Call<UpdateResponse> updateDetails(@Body UpdateRequest request, @Header("X-TOKEN") String token);

}

Now How can i bind the details and send.

Please Help me..


回答1:


You have to create Multipart Request like below.

File file = new File(filePath);

RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("picture", file.getName(), reqFile);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "picture");

RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "your_name"); 
RequestBody email = RequestBody.create(MediaType.parse("text/plain"), "your_email"); 
RequestBody phone = RequestBody.create(MediaType.parse("text/plain"), "your_phone"); 

HasMap<String,RequestBody> map = new HasMap<>();
map.put("name",name);
map.put("email",email);
map.put("phone",phone);


postImage(map, picture)

Interface is like below.

@Multipart
    @PUT("/")
    Call<ResponseBody> postImage(@PartMap Map<String, RequestBody> map, @Part MultipartBody.Part image);
}

Also, don't forget to add @Multipart in your interface.



来源:https://stackoverflow.com/questions/44951054/image-upload-using-retrofit2-put-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!