POST Multipart Form Data using Retrofit 2.0 including image
I am highlighting the solution in both 1.9 and 2.0 since it is useful for some
In 1.9
, I think the better solution is to save the file to disk and use it as Typed file like:
(I don't know about your server-side implementation) have an API interface method similar to this
@POST("/en/Api/Results/UploadFile")
void UploadFile(@Part("file") TypedFile file,
@Part("folder") String folder,
Callback<Response> callback);
And use it like
TypedFile file = new TypedFile("multipart/form-data",
new File(path));
For RetroFit 2 Use the following methodRetroFit 2.0 ( This was a workaround for an issue in RetroFit 2 which is fixed now, for the correct method refer jimmy0251's answer)API Interface:
public interface ApiInterface {
@Multipart
@POST("/api/Accounts/editaccount")
Call<User> editUser(@Header("Authorization") String authorization,
@Part("file\"; filename=\"pp.png\" ") RequestBody file,
@Part("FirstName") RequestBody fname,
@Part("Id") RequestBody id);
}
Use it like:
File file = new File(imageUri.getPath());
RequestBody fbody = RequestBody.create(MediaType.parse("image/*"),
file);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"),
firstNameField.getText()
.toString());
RequestBody id = RequestBody.create(MediaType.parse("text/plain"),
AZUtils.getUserId(this));
Call<User> call = client.editUser(AZUtils.getToken(this),
fbody,
name,
id);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(retrofit.Response<User> response,
Retrofit retrofit) {
AZUtils.printObject(response.body());
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
});
POST data using the Content-Type multipart/form-data
Related Topics
How to Save/Download Pdf Embedded in Web Page Without a Pdf Filename
Remove Surrounding Whitespace from an Image
Controlling Datetime Parameter Formatting in Webapi 2
Could Not Start Windows Service, Error 1064
Using Formflow Dialog in Bot Framework
Find First Digit of a Number Using Only Integer Operations
Deserialize Json String in to Multiple C# Objects
Regular Expression for Valid Filename
How to Cast Object to List<Object> and Turn It into an Array
C#: How to Force Trailing Zero in Numeric Format String
How to Reference Assemblies Using Visual Studio Code
C# How to Split a List in Two Using Linq
How Does Httpcontext.Current.User.Identity.Name Know Which Usernames Exist
Why Does Integer Division in C# Return an Integer and Not a Float