Upload an Image and Audio in One Request in Android

upload an image and audio in One request in android

Just use the httpmime-4.0.jar and apache-mime4j-0.4.jar and set the entity as MultipartEntity.
you can use as many file as you want.

Here is the stuff,

HttpPost httpost = new HttpPost("url for upload file");

MultipartEntity entity = new MultipartEntity();
entity.addPart("myIdentifier", new StringBody("somevalue"));
entity.addPart("myImageFile", new FileBody(imageFile));
entity.addPart("myAudioFile", new FileBody(audioFile));

httpost.setEntity(entity);
HttpResponse response;
response = httpclient.execute(httpost);

and for php side you can use these entity identifier names "myImageFile" and "myAudioFile" and move these files in appropriate folder.

How to post audio and image as multipart/formdata in native android?

Here I created an example using Volley
So first of all we have to build a RestApiMultiPartRequests.class so here i created it like this

private class RestApiMultiPartRequests extends Request {

private final Map<String, String> mStringParts;
private final Map<String, File> mFileParts;
private MultipartEntityBuilder mBuilder;
private final Response.Listener<T> mListener;

public RestApiMultiPartRequests(String url,
Map<String, String> stringParts,
Map<String, File> fileParts,
Response.Listener<T> listener,
Response.ErrorListener errorListener) {
super(Method.POST, url, errorListener);
mListener = listener;
mStringParts = stringParts;
mFileParts = fileParts;
buildMultipartEntity();
}

private void buildMultipartEntity() {
if (mBuilder != null) {
mBuilder = null;
}
mBuilder = MultipartEntityBuilder.create();
mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mBuilder.setBoundary("_____" + Long.toString(System.currentTimeMillis()) + "_____");
mBuilder.setCharset(Consts.UTF_8);
if (mStringParts != null) {
for (Map.Entry<String, String> entry : mStringParts.entrySet()) {
mBuilder.addTextBody(entry.getKey(), entry.getValue(), ContentType.create("text/plain", Charset.forName("UTF-8")));
}
}

Log.e("Size", "Size: " + mFileParts.size());
for (Map.Entry<String, File> entry : mFileParts.entrySet()) {
ContentType imageContentType = ContentType.create("image/*");//MULTIPART_FORM_DATA;
Log.d("", "Key " + entry.getKey());
Log.d("", "Value " + entry.getValue());
Log.d("", "Name " + entry.getValue().getName());
//"userfile"
mBuilder.addBinaryBody(entry.getKey(), entry.getValue(), imageContentType, entry.getValue().getName());
}
}

@Override
public String getBodyContentType() {
return mBuilder.build().getContentType().getValue();
}

@Override
public byte[] getBody() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
mBuilder.build().writeTo(bos);
} catch (IOException e) {
e.printStackTrace();
}

return bos.toByteArray();
}

public HttpEntity getEntity() {
return mBuilder.build();
}

@SuppressWarnings("unchecked")
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return (Response<T>) Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}

@Override
protected void deliverResponse(T response) {
mListener.onResponse(response);

}

}

Using this class we can build a request like this

 private void UploadImage() {

ServiceCall.RestApiMultiPartRequests<String> restApiMultiPartRequest =
new ServiceCall.RestApiMultiPartRequests<String>(url/*YOUR SERVICE URL*/, hashMap /* HASHMAP OF STRING */, fileparts /*HASH MAP OF FILE AND STRING */, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
/* HANDEL YOUR SUCCESS RESPONSE **/
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Handle your error types accordingly.For Timeout & No
// connection error, you can show 'retry' button.
// For AuthFailure, you can re login with user
// credentials.
// For ClientError, 400 & 401, Errors happening on
// client side when sending api request.
// In this case you can check how client is forming the
// api and debug accordingly.
// For ServerError 5xx, you can do retry or handle
// accordingly.

/** HANDLE YOUR ERRORS */
}
}) {

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization","YOUR AUTHANTICATION TOKEN IF REQUIRED");
return params;
}

@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};

restApiMultiPartRequest.setRetryPolicy(new DefaultRetryPolicy(0, 1, 2));//10000
VOLLEY_INSTANCE.addToRequestQueue(restApiMultiPartRequest);
}

Here hashmap is HashMap<String, String> hashMap
and fileparts is HashMap<String, File> fileparts;

so the parameters with String key and String value add in to hashmap
and parameters with String key and File Value add into fileparts

Send file to server via retrofit2 as object

For finding How to send your file to Server via Retroit following steps may solve your problem:

1- Install PostMan.

2- In PostMan select Post and paste URL then go to Body tab and choose form-data.

3- In Key's part write server file name and In Value's part set type as File and upload desire file.

Sample Image

4- Click in Send and then Generate code.

5- Now you have something like following:

Sample Image

6- Now just one step remain go to your retrofit service and paste info like (In my case I want to upload audio.mp3) :

    @Multipart
@POST("app/")
Call<JResponse> upload(@Part("file\"; filename=\"audio.mp3\" ") RequestBody file);

And request body would be something like:

File file = new File("YOUR_PATH");
RequestBody temp = RequestBody.create(MediaType.parse("multipart/form-data"), file);

Use this pattern and send it with:

 ServiceHelper.getInstance().sendAudio(temp).enqueue(new Callback<JResponse>() {
@Override
public void onResponse(Call<JResponse> call, Response<JResponse> response) {
Log.e("test", "onResponse: tst");

}

@Override
public void onFailure(Call<JResponse> call, Throwable t) {
Log.e("test", "onResponse: tst");

}
});

Uploading Image and Audio in form data with OKhttp giving me BadRequest Status 400

well the error was in the request body.

   RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addFormDataPart("file", file.getName(),
RequestBody.create(MediaType.parse("image/jpg"), file))
.addFormDataPart(caseId+"_audio", caseId+"_audio",
RequestBody.create(MediaType.parse("audio/*"), Audio))
.build();

Changed this line

 .addFormDataPart(caseId+"_audio", caseId+"_audio",
RequestBody.create(MediaType.parse("audio/*"), Audio))
.build();

to

   .addFormDataPart(caseId+"_audio", Audio.getName(),
RequestBody.create(MediaType.parse("audio/*"), Audio))
.build();

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:

RetroFit 1.9

(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 method

RetroFit 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();
}
});


Related Topics



Leave a reply



Submit