问题
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