简体   繁体   English

使用Retrofit2 Put方法上传图像

[英]Image upload using retrofit2 Put method

I am new to retrofit2. 我是改造2的新手。 I want upload image through api service as a file. 我想通过api服务将图像上传为文件。 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 这是Api的Header部分

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

In the body section I am having, "picture", "name", "email" and "phone" 在正文部分,我有"picture", "name", "email" and "phone"

I am trying like, 我正在尝试

i have created a class with body parameters UpdateRequest Class 我创建了一个带有身体参数UpdateRequest类的类

    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 api接口功能

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.. 请帮我..

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. 另外,不要忘记在界面中添加@Multipart。

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

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