繁体   English   中英

使用Retrofit2 Put方法上传图像

[英]Image upload using retrofit2 Put method

我是改造2的新手。 我想通过api服务将图像上传为文件。 我已尝试通过选择文件来与邮递员联系,并发现其工作正常。 但是如何通过手机上传图像文件。

这是Api的Header部分

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

在正文部分,我有"picture", "name", "email" and "phone"

我正在尝试

我创建了一个带有身体参数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接口功能

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);

}

现在如何绑定详细信息并发送。

请帮我..

您必须创建如下所示的分段请求。

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)

界面如下。

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

另外,不要忘记在界面中添加@Multipart。

暂无
暂无

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

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