I have an image and I want to upload this image to my web service using Volley library, the problem is I'm looking for a how to do it but still haven't found.
I found this, but doesn't work to me: http://develop-for-android.blogspot.com.br/2014/01/using-volley-in-your-application.html
How can I do this ?
I'm trying this.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
fotoPerfil = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
UploadoImageToServer upload = new UploadoImageToServer();
ApplicationController app = new UsuarioDAO().insert(usuario, upload.upload(fotoPerfil, em[0]), new UsuarioAdapter(){
#Override
public void usuarioIsAdded(Boolean result){
Log.i("Adicionou: ", result + "");
progress.dismiss();
}
});
CustomVolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(app);
public class UploadoImageToServer {
public String upload(String image,String nomeImagem){
Bitmap bitmap = BitmapFactory.decodeFile(image);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
return image_str;
}
}
/** add an user and upload your foto(image) */
public ApplicationController insert(Usuario u, String uploadFile, final UsuarioAdapter listener) {
boolean insert = false;
HashMap<String, String> params = new HashMap<String, String>();
params.put("nome", u.getNome());
params.put("email", u.getEmail());
params.put("senha", u.getSenha());
params.put("tipo", "usuarios");
params.put("acao", "add");
params.put("device_tipo", "android");
params.put("device", AndroidReturnId.getAndroidId());
params.put("uploadedfile", uploadFile);
Log.i("URL: ", urlPost.toString());
ApplicationController apc = new ApplicationController(Method.POST, urlPost.toString(), params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject obj) {
try {
if(obj.getString("cod").equals("999")){
listener.usuarioIsAdded(true);
}else{
listener.usuarioIsAdded(false);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
Log.e("ERROR METHOD:", "insert in UsuarioDAO: " + arg0.getLocalizedMessage());
}
});
return apc;
}
i am not much familier with volley, but give a try to the following code
//JSON Request
public MySampleImageUpload() {
JSONRequestResponse mResponse = new
JSONRequestResponse(mContext);
Bundle parms = new Bundle();
parms.putString("key_meail", "rojesh#demo.com");
parms.setFile("key_url", image_path);
mResponse.getResponse("sample_upload_data_url", REQUEST_CODE, this,
parms);
}
// In SetFile & getResponse code
package com.fartogram.utils;
import java.io.File;
import org.json.JSONObject;
import android.content.Context;
import android.os.Bundle;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.examples.toolbox.MultipartRequest;
import com.android.volley.examples.toolbox.MyVolley;
import com.android.volley.toolbox.JsonObjectRequest;
public class JSONRequestResponse {
public JSONRequestResponse(Context cntx) {
mContext = cntx;
}
private final Context mContext;
private int reqCode;
private IParseListener listner;
private boolean isFile = false;
private String file_path = "", key = "";
public void getResponse(String url, final int requestCode,
IParseListener mParseListener) {
getResponse(url, requestCode, mParseListener, null);
}
public void getResponse(String url, final int requestCode,
IParseListener mParseListener, Bundle params) {
this.listner = mParseListener;
this.reqCode = requestCode;
Response.Listener<JSONObject> sListener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (listner != null) {
listner.SuccessResponse(response, reqCode);
}
}
};
Response.ErrorListener eListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (listner != null) {
listner.ErrorResponse(error, reqCode);
}
}
};
if (!isFile) {
JsonObjectRequest jsObjRequest = new JsonObjectRequest(
Request.Method.GET, url, null, sListener,
eListener);
MyVolley.getRequestQueue().add(jsObjRequest);
} else {
if (file_path != null) {
File mFile = new File(file_path);
MultipartRequest multipartRequest =
new MultipartRequest(url,eListener, sListener, key, mFile, params);
MyVolley.getRequestQueue().add(multipartRequest);
}
}
}
public boolean isFile() {
return isFile;
}
public void setFile(String param, String path) {
if (path != null && param != null) {
key = param;
file_path = path;
this.isFile = true;
}
}
}
If it works for you mark it as right :)
You have to extend Request and use MultipartEntityBuilder if you wanna upload your image as a file.
public class ImageUploadWithVolley<T> extends Request<T> {
private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
private final Response.Listener<T> mListener;
private final File yourImageFile;
protected Map<String, String> headers;
public ImageUploadWithVolley(String url, ErrorListener errorListener, Listener<T> listener, File imageFile) {
super(Method.POST, url, errorListener);
mListener = listener;
yourImageFile = imageFile;
addImageEntity();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
headers.put("Accept", "application/json");
return headers;
}
private void addImageEntity() {
mBuilder.addBinaryBody("give your image name", yourImageFile, ContentType.create("image/jpeg"), yourImageFile.getName());
mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mBuilder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));
}
#Override
public String getBodyContentType() {
String content = mBuilder.build().getContentType().getValue();
return content;
}
#Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
mBuilder.build().writeTo(bos);
} catch (IOException e){
VolleyLog.e("IOException writing to ByteArrayOutputStream bos, building the multipart request.");
}
return bos.toByteArray();
}
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response){
T result = null;
return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
}
#Override
protected void deliverResponse(T response) {
mListener.onResponse(response);
}
}
Related
Ok so what I am trying to do is to open an image, set it in an imageview and make it a file in order to send it in a multipartform request using volley, right now I am using PostMan to make Http Requests to my server (string and file) and it is working properly but I can not implement it in android what I have so far is this
public void onClick(View v) {
if(v == banner){
Intent intent = new Intent();
//Verified the android version
if(Build.VERSION.SDK_INT < 19){
intent.setAction(Intent.ACTION_GET_CONTENT);
} else{
//KitKat 4.4 o superior
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
}
intent.setType("image/*");
startActivityForResult(intent, request_code);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK && requestCode == request_code) {
uri = data.getData();
banner.setImageURI(uri);
//TAG for store the Uri to the selected file
banner.setTag(uri);
path = uri.getPath();
fileImage = new File (path);
Toast.makeText(this,path,Toast.LENGTH_LONG).show();}
Where banner is my imageview and fileImage is my file
MultipartRequest myRequest = new MultipartRequest(
"MY_URL",
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("error");
}
},
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.e(response);
}
},
fileImage,
params
);
I am using this class that was answered in another question
public class MultipartRequest extends Request<String> {
//private MultipartEntity entity = new MultipartEntity();
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
HttpEntity httpentity;
private static final String FILE_PART_NAME = "banner";
private final Response.Listener<String> mListener;
private final File mFilePart;
private final Map<String, String> mStringPart;
public MultipartRequest(String url, Response.ErrorListener errorListener,
Response.Listener<String> listener,
File file,
Map<String, String> mStringPart) {
super(Method.POST, url, errorListener);
mListener = listener;
mFilePart = file;
this.mStringPart = mStringPart;
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
buildMultipartEntity();
}
public void addStringBody(String param, String value) {
mStringPart.put(param, value);
}
private void buildMultipartEntity() {
entity.addPart(FILE_PART_NAME, new FileBody(mFilePart));
for (Map.Entry<String, String> entry : mStringPart.entrySet()) {
entity.addTextBody(entry.getKey(), entry.getValue());
}
}
#Override
public String getBodyContentType() {
return httpentity.getContentType().getValue();
}
#Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
httpentity = entity.build();
httpentity.writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
return Response.success("Uploaded", getCacheEntry());
}
#Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
}
But it return me the error "IOException writing to ByteArrayOutputStream"
If your goal is just saving the image to file, take a look at this post, you need to turn the image received as a bitmap first and then just follow what's written in that post
I am trying to upload image from camera and gallery using multipart data http post using volley, but the image taken from camera is not getting uploaded whereas from the gallery is uploaded.
private void startCamera() {
Intent imageIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(imageIntent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch (requestCode) {
case CAMERA_CAPTURE_IMAGE_REQUEST_CODE:
if(resultCode== Activity.RESULT_OK){
previewCapturedImage();
}else{
Toast.makeText(getActivity(),"User cancelled image capture", Toast.LENGTH_SHORT).show();
}
break;
}
private void previewCapturedImage() {
try {
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
filePath=fileUri.getPath();
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, options.outWidth, options.outHeight, matrix, true);
postImageView.setImageBitmap(rotatedBitmap);
((TextView)appView.findViewById(R.id.deleteBtn)).setVisibility(View.VISIBLE);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
public void postFeed(String commentString){
RequestQueue mqueue = Volley.newRequestQueue(getActivity());
Map<String, String> params = new HashMap<String, String>();
params.put("text",commentString);
params.put("user_id",SettingsHelper.getInstance(getActivity()).getPreference("id"));
TSUServerRequest.postFeed(getActivity(),mqueue,params,new File(filePath),new Response.Listener<String>() {
#Override
public void onResponse(String s) {
Log.d("a","bscljk");
filePath="";
fileUri= null;
//Toast.makeText(getActivity(),"Success",Toast.LENGTH_LONG).show();
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
volleyError.printStackTrace();
}
});
public static void postFeed(Context context,RequestQueue queue,Map<String, String> params,File file,
Listener<String> listener, ErrorListener errorListener){
if (TSUServerRequest.checkForConnection(context)) {
String url =API_CREATE_POST;
MultiPartRequest myReq = new MultiPartRequest(url,errorListener,listener,file,params);
queue.add(myReq);
queue.start();
}else{
Toast.makeText(context, "No Internet!Please try again!", Toast.LENGTH_LONG).show();
}
}
////MultipartRequest.java
public class MultiPartRequest extends Request<String> {
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
HttpEntity httpentity;
private static final String FILE_PART_NAME = "picture";
private final Response.Listener<String> mListener;
private final File mFilePart;
private final Map<String, String> mStringPart;
public MultiPartRequest(String url, Response.ErrorListener errorListener,
Response.Listener<String> listener, File file,
Map<String, String> mStringPart) {
super(Method.POST, url, errorListener);
mListener = listener;
mFilePart = file;
this.mStringPart = mStringPart;
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
buildMultipartEntity();
}
public void addStringBody(String param, String value) {
mStringPart.put(param, value);
}
private void buildMultipartEntity() {
entity.addPart(FILE_PART_NAME, new FileBody(mFilePart));
for (Map.Entry<String, String> entry : mStringPart.entrySet()) {
entity.addTextBody(entry.getKey(), entry.getValue());
}
}
#Override
public String getBodyContentType() {
return httpentity.getContentType().getValue();
}
#Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
httpentity = entity.build();
httpentity.writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
return Response.success("Uploaded", getCacheEntry());
}
#Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
}
The reason image was not getting uploaded was size.
Image file immediately taken from camera is too big in size and hence needs to be compressed.
The same file when picked from gallery gets uploaded because gallery internally compresses the files.
public File compress(){
File file = new File(filePath);
try {
Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath());
if(flagCamera==1) {
flagCamera=0;
compressedFile = new File(Environment.getExternalStorageDirectory().toString() + "/compressed" + file.getName());
FileOutputStream out = new FileOutputStream(compressedFile);
bitmap.compress(Bitmap.CompressFormat.JPEG,70,out);
out.flush();
out.close();
}else{
return file;
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return compressedFile;
}
public void postFeed(String commentString) {
RequestQueue mqueue = Volley.newRequestQueue(getActivity());
Map<String, String> params = new HashMap<String, String>();
params.put("access_token", SettingsHelper.getInstance(getActivity()).getPreference("auth_token"));
params.put("text", commentString);
params.put("user_id", SettingsHelper.getInstance(getActivity()).getPreference("id"));
params.put("privacy", Integer.toString(1));
TSUServerRequest.postFeed(getActivity(), mqueue, params, compress(), new Response.Listener<String>() {
#Override
public void onResponse(String s) {
Log.d("a", "bscljk");
filePath = "";
fileUri = null;
//Toast.makeText(getActivity(),"Success",Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
volleyError.printStackTrace();
}
});
}
I have tried to upload multiple images using volley library in a single web service. but, only the last image is getting uploaded. Those previous images are getting replaced with the null. I want to know is it possible with volley library, if not can you plz suggest me other libraries. I'm a newbie to android I only know volley for uploading images.
//JSON Request
public MySampleImageUpload() {
JSONRequestResponse mResponse = new JSONRequestResponse(mContext);
Bundle parms = new Bundle();
parms.putString("key_meail", "rojesh#demo.com");
parms.setFile("key_url", image_path);
mResponse.getResponse("sample_upload_data_url", REQUEST_CODE, this,
parms);
}
// In SetFile & getResponse code
package com.fartogram.utils;
import java.io.File;
import org.json.JSONObject;
import android.content.Context;
import android.os.Bundle;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.examples.toolbox.MultipartRequest;
import com.android.volley.examples.toolbox.MyVolley;
import com.android.volley.toolbox.JsonObjectRequest;
public class JSONRequestResponse {
public JSONRequestResponse(Context cntx) {
mContext = cntx;
}
private final Context mContext;
private int reqCode;
private IParseListener listner;
private boolean isFile = false;
private String file_path = "", key = "";
public void getResponse(String url, final int requestCode,
IParseListener mParseListener) {
getResponse(url, requestCode, mParseListener, null);
}
public void getResponse(String url, final int requestCode,
IParseListener mParseListener, Bundle params) {
this.listner = mParseListener;
this.reqCode = requestCode;
Response.Listener<JSONObject> sListener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (listner != null) {
listner.SuccessResponse(response, reqCode);
}
}
};
Response.ErrorListener eListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (listner != null) {
listner.ErrorResponse(error, reqCode);
}
}
};
if (!isFile) {
JsonObjectRequest jsObjRequest = new JsonObjectRequest(
Request.Method.GET, url, null, sListener,
eListener);
MyVolley.getRequestQueue().add(jsObjRequest);
} else {
if (file_path != null) {
File mFile = new File(file_path);
MultipartRequest multipartRequest =
new MultipartRequest(url,eListener, sListener, key, mFile, params);
MyVolley.getRequestQueue().add(multipartRequest);
}
}
}
public boolean isFile() {
return isFile;
}
public void setFile(String param, String path) {
if (path != null && param != null) {
key = param;
file_path = path;
this.isFile = true;
}
}
}
public class CustomMultiRequest extends Request<JSONObject> {
private MultipartEntity entity = new MultipartEntity();
private static final String FILE_PART_NAME = "postfieldname[]";
private final Response.Listener<JSONObject> mListener;
private final ArrayList<File> mFilePart;
private final ArrayList<PostEntityModel> mStringPart;
public CustomMultiRequest(String url, Response.ErrorListener errorListener, Response.Listener<JSONObject> listener,ArrayList<File> files, ArrayList<PostEntityModel> stringPart)
{
super(Method.POST, url, errorListener);
mListener = listener;
mFilePart = files;
mStringPart = stringPart;
buildMultipartEntity();
}
private void buildMultipartEntity()
{
for (File file : mFilePart){
entity.addPart(FILE_PART_NAME, new FileBody(file));
}
try
{
for(PostEntityModel postEntityModel : mStringPart){
entity.addPart(postEntityModel.getName(), new StringBody(postEntityModel.getValue()));
}
}
catch (UnsupportedEncodingException e)
{
VolleyLog.e("UnsupportedEncodingException");
}
}
#Override
public String getBodyContentType()
{
return entity.getContentType().getValue();
}
#Override
public byte[] getBody() throws AuthFailureError
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try
{
entity.writeTo(bos);
}
catch (IOException e)
{
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response)
{
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONObject response)
{
mListener.onResponse(response);
}
}
If you use Gradle, add this to your build.gradle file:
compile('org.apache.httpcomponents:httpmime:4.3.6') {
exclude module: 'httpclient'
}
compile 'org.apache.httpcomponents:httpclient-android:4.3.5'
Has anyone been able to accomplish sending a multipart/form-data POST in Android with Volley yet? I have had no success trying to upload an image/png using a POST request to our server and am curious if anyone has.
I believe the default way to do this would be to override public byte[] getPostBody() in the Request.java class and attach the File there with a blank Header key for the boundary. However, converting my file to a String for the Map<String, String> postParams and then having it encoded again seems obtuse and not really elegant. Also I've been unsuccessful in my attempts. This is really the only thing holding us back from switching to this library.
Anyway, all thoughts and answers are extremely appreciated. Thank you for your help.
I might be wrong on this but I think you need to implement your own com.android.volley.toolbox.HttpStack for this because the default ones (HurlStack if version > Gingerbread or HttpClientStack) don't deal with multipart/form-data.
Edit:
And indeed I was wrong. I was able to do it using MultipartEntity in Request like this:
public class MultipartRequest extends Request<String> {
private MultipartEntity entity = new MultipartEntity();
private static final String FILE_PART_NAME = "file";
private static final String STRING_PART_NAME = "text";
private final Response.Listener<String> mListener;
private final File mFilePart;
private final String mStringPart;
public MultipartRequest(String url, Response.ErrorListener errorListener, Response.Listener<String> listener, File file, String stringPart)
{
super(Method.POST, url, errorListener);
mListener = listener;
mFilePart = file;
mStringPart = stringPart;
buildMultipartEntity();
}
private void buildMultipartEntity()
{
entity.addPart(FILE_PART_NAME, new FileBody(mFilePart));
try
{
entity.addPart(STRING_PART_NAME, new StringBody(mStringPart));
}
catch (UnsupportedEncodingException e)
{
VolleyLog.e("UnsupportedEncodingException");
}
}
#Override
public String getBodyContentType()
{
return entity.getContentType().getValue();
}
#Override
public byte[] getBody() throws AuthFailureError
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try
{
entity.writeTo(bos);
}
catch (IOException e)
{
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response)
{
return Response.success("Uploaded", getCacheEntry());
}
#Override
protected void deliverResponse(String response)
{
mListener.onResponse(response);
}
}
It's pretty raw but I tried it with an image and a simple string and it works. The response is a placeholder, doesn't make much sense to return a Response String in this case. I had problems using apache httpmime to use MultipartEntity so I used this https://code.google.com/p/httpclientandroidlib/ don't know if there's a better way.
Hope it helps.
Edit
You can use httpmime without using httpclientandroidlib, the only dependency is httpcore.
As mentioned in the presentation at the I/O (about 4:05), Volley "is terrible" for large payloads. As I understand it that means not to use Volley for receiving/sending (big) files. Looking at the code it seems that it is not even designed to handle multipart form data (e.g. Request.java has getBodyContentType() with hardcoded "application/x-www-form-urlencoded"; HttpClientStack::createHttpRequest() can handle only byte[], etc...). Probably you will be able to create implementation that can handle multipart but If I were you I will just use HttpClient directly with MultipartEntity like:
HttpPost req = new HttpPost(composeTargetUrl());
MultipartEntity entity = new MultipartEntity();
entity.addPart(POST_IMAGE_VAR_NAME, new FileBody(toUpload));
try {
entity.addPart(POST_SESSION_VAR_NAME, new StringBody(uploadSessionId));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
req.setEntity(entity);
You may need newer HttpClient (i.e. not the built-in) or even better, use Volley with newer HttpClient
UPDATE 2015/08/26:
If you don't want to use deprecated HttpEntity, here is my working sample code (tested with ASP.Net WebAPI)
MultipartActivity.java
package com.example.volleyapp;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.Menu;
import android.view.MenuItem;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.example.volleyapp.BaseVolleyRequest;
import com.example.volleyapp.VolleySingleton;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public class MultipartActivity extends Activity {
final Context mContext = this;
String mimeType;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String boundary = "apiclient-" + System.currentTimeMillis();
String twoHyphens = "--";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1024 * 1024;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multipart);
Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.ic_action_file_attachment_light);
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
final byte[] bitmapData = byteArrayOutputStream.toByteArray();
String url = "http://192.168.1.100/api/postfile";
mimeType = "multipart/form-data;boundary=" + boundary;
BaseVolleyRequest baseVolleyRequest = new BaseVolleyRequest(1, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public String getBodyContentType() {
return mimeType;
}
#Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
dos = new DataOutputStream(bos);
try {
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ "ic_action_file_attachment_light.png" + "\"" + lineEnd);
dos.writeBytes(lineEnd);
ByteArrayInputStream fileInputStream = new ByteArrayInputStream(bitmapData);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return bitmapData;
}
};
VolleySingleton.getInstance(mContext).addToRequestQueue(baseVolleyRequest);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_multipart, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
BaseVolleyRequest.java:
package com.example.volleyapp;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.JsonSyntaxException;
public class BaseVolleyRequest extends Request<NetworkResponse> {
private final Response.Listener<NetworkResponse> mListener;
private final Response.ErrorListener mErrorListener;
public BaseVolleyRequest(String url, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
super(0, url, errorListener);
this.mListener = listener;
this.mErrorListener = errorListener;
}
public BaseVolleyRequest(int method, String url, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.mListener = listener;
this.mErrorListener = errorListener;
}
#Override
protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
try {
return Response.success(
response,
HttpHeaderParser.parseCacheHeaders(response));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
} catch (Exception e) {
return Response.error(new ParseError(e));
}
}
#Override
protected void deliverResponse(NetworkResponse response) {
mListener.onResponse(response);
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
return super.parseNetworkError(volleyError);
}
#Override
public void deliverError(VolleyError error) {
mErrorListener.onErrorResponse(error);
}
}
END OF UPDATE
This is my working sample code (only tested with small-size files):
public class FileUploadActivity extends Activity {
private final Context mContext = this;
HttpEntity httpEntity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file_upload);
Drawable drawable = getResources().getDrawable(R.drawable.ic_action_home);
if (drawable != null) {
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
final byte[] bitmapdata = stream.toByteArray();
String url = "http://10.0.2.2/api/fileupload";
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
// Add binary body
if (bitmapdata != null) {
ContentType contentType = ContentType.create("image/png");
String fileName = "ic_action_home.png";
builder.addBinaryBody("file", bitmapdata, contentType, fileName);
httpEntity = builder.build();
MyRequest myRequest = new MyRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
Toast.makeText(mContext, jsonString, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mContext, error.toString(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
public String getBodyContentType() {
return httpEntity.getContentType().getValue();
}
#Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
httpEntity.writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
};
MySingleton.getInstance(this).addToRequestQueue(myRequest);
}
}
}
...
}
public class MyRequest extends Request<NetworkResponse>
Complete Multipart Request with Upload Progress
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.util.CharsetUtils;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.beusoft.app.AppContext;
public class MultipartRequest extends Request<String> {
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
HttpEntity httpentity;
private String FILE_PART_NAME = "files";
private final Response.Listener<String> mListener;
private final File mFilePart;
private final Map<String, String> mStringPart;
private Map<String, String> headerParams;
private final MultipartProgressListener multipartProgressListener;
private long fileLength = 0L;
public MultipartRequest(String url, Response.ErrorListener errorListener,
Response.Listener<String> listener, File file, long fileLength,
Map<String, String> mStringPart,
final Map<String, String> headerParams, String partName,
MultipartProgressListener progLitener) {
super(Method.POST, url, errorListener);
this.mListener = listener;
this.mFilePart = file;
this.fileLength = fileLength;
this.mStringPart = mStringPart;
this.headerParams = headerParams;
this.FILE_PART_NAME = partName;
this.multipartProgressListener = progLitener;
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
try {
entity.setCharset(CharsetUtils.get("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
buildMultipartEntity();
httpentity = entity.build();
}
// public void addStringBody(String param, String value) {
// if (mStringPart != null) {
// mStringPart.put(param, value);
// }
// }
private void buildMultipartEntity() {
entity.addPart(FILE_PART_NAME, new FileBody(mFilePart, ContentType.create("image/gif"), mFilePart.getName()));
if (mStringPart != null) {
for (Map.Entry<String, String> entry : mStringPart.entrySet()) {
entity.addTextBody(entry.getKey(), entry.getValue());
}
}
}
#Override
public String getBodyContentType() {
return httpentity.getContentType().getValue();
}
#Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
httpentity.writeTo(new CountingOutputStream(bos, fileLength,
multipartProgressListener));
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
try {
// System.out.println("Network Response "+ new String(response.data, "UTF-8"));
return Response.success(new String(response.data, "UTF-8"),
getCacheEntry());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
// fuck it, it should never happen though
return Response.success(new String(response.data), getCacheEntry());
}
}
#Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
//Override getHeaders() if you want to put anything in header
public static interface MultipartProgressListener {
void transferred(long transfered, int progress);
}
public static class CountingOutputStream extends FilterOutputStream {
private final MultipartProgressListener progListener;
private long transferred;
private long fileLength;
public CountingOutputStream(final OutputStream out, long fileLength,
final MultipartProgressListener listener) {
super(out);
this.fileLength = fileLength;
this.progListener = listener;
this.transferred = 0;
}
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
if (progListener != null) {
this.transferred += len;
int prog = (int) (transferred * 100 / fileLength);
this.progListener.transferred(this.transferred, prog);
}
}
public void write(int b) throws IOException {
out.write(b);
if (progListener != null) {
this.transferred++;
int prog = (int) (transferred * 100 / fileLength);
this.progListener.transferred(this.transferred, prog);
}
}
}
}
Sample Usage
protected <T> void uploadFile(final String tag, final String url,
final File file, final String partName,
final Map<String, String> headerParams,
final Response.Listener<String> resultDelivery,
final Response.ErrorListener errorListener,
MultipartProgressListener progListener) {
AZNetworkRetryPolicy retryPolicy = new AZNetworkRetryPolicy();
MultipartRequest mr = new MultipartRequest(url, errorListener,
resultDelivery, file, file.length(), null, headerParams,
partName, progListener);
mr.setRetryPolicy(retryPolicy);
mr.setTag(tag);
Volley.newRequestQueue(this).add(mr);
}
A very simple approach for the dev who just want to send POST parameters in multipart request.
Make the following changes in class which extends Request.java
First define these constants :
String BOUNDARY = "s2retfgsGSRFsERFGHfgdfgw734yhFHW567TYHSrf4yarg"; //This the boundary which is used by the server to split the post parameters.
String MULTIPART_FORMDATA = "multipart/form-data;boundary=" + BOUNDARY;
Add a helper function to create a post body for you :
private String createPostBody(Map<String, String> params) {
StringBuilder sbPost = new StringBuilder();
if (params != null) {
for (String key : params.keySet()) {
if (params.get(key) != null) {
sbPost.append("\r\n" + "--" + BOUNDARY + "\r\n");
sbPost.append("Content-Disposition: form-data; name=\"" + key + "\"" + "\r\n\r\n");
sbPost.append(params.get(key).toString());
}
}
}
return sbPost.toString();
}
Override getBody() and getBodyContentType
public String getBodyContentType() {
return MULTIPART_FORMDATA;
}
public byte[] getBody() throws AuthFailureError {
return createPostBody(getParams()).getBytes();
}
First answer on SO.
I have encountered the same problem and found #alex 's code very helpful. I have made some simple modifications in order to pass in as many parameters as needed through HashMap, and have basically copied parseNetworkResponse() from StringRequest. I have searched online and so surprised to find out that such a common task is so rarely answered. Anyway, I wish the code could help:
public class MultipartRequest extends Request<String> {
private MultipartEntity entity = new MultipartEntity();
private static final String FILE_PART_NAME = "image";
private final Response.Listener<String> mListener;
private final File file;
private final HashMap<String, String> params;
public MultipartRequest(String url, Response.Listener<String> listener, Response.ErrorListener errorListener, File file, HashMap<String, String> params)
{
super(Method.POST, url, errorListener);
mListener = listener;
this.file = file;
this.params = params;
buildMultipartEntity();
}
private void buildMultipartEntity()
{
entity.addPart(FILE_PART_NAME, new FileBody(file));
try
{
for ( String key : params.keySet() ) {
entity.addPart(key, new StringBody(params.get(key)));
}
}
catch (UnsupportedEncodingException e)
{
VolleyLog.e("UnsupportedEncodingException");
}
}
#Override
public String getBodyContentType()
{
return entity.getContentType().getValue();
}
#Override
public byte[] getBody() throws AuthFailureError
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try
{
entity.writeTo(bos);
}
catch (IOException e)
{
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
/**
* copied from Android StringRequest class
*/
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
#Override
protected void deliverResponse(String response)
{
mListener.onResponse(response);
}
And you may use the class as following:
HashMap<String, String> params = new HashMap<String, String>();
params.put("type", "Some Param");
params.put("location", "Some Param");
params.put("contact", "Some Param");
MultipartRequest mr = new MultipartRequest(url, new Response.Listener<String>(){
#Override
public void onResponse(String response) {
Log.d("response", response);
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley Request Error", error.getLocalizedMessage());
}
}, f, params);
Volley.newRequestQueue(this).add(mr);
Another solution, very light with high performance with payload large:
Android Asynchronous Http Client library:
http://loopj.com/android-async-http/
private static AsyncHttpClient client = new AsyncHttpClient();
private void uploadFileExecute(File file) {
RequestParams params = new RequestParams();
try { params.put("photo", file); } catch (FileNotFoundException e) {}
client.post(getUrl(), params,
new AsyncHttpResponseHandler() {
public void onSuccess(String result) {
Log.d(TAG,"uploadFile response: "+result);
};
public void onFailure(Throwable arg0, String errorMsg) {
Log.d(TAG,"uploadFile ERROR!");
};
}
);
}
Here is Simple Solution And Complete Example for Uploading File Using Volley Android
1) Gradle Import
compile 'dev.dworks.libs:volleyplus:+'
2)Now Create a Class RequestManager
public class RequestManager {
private static RequestManager mRequestManager;
/**
* Queue which Manages the Network Requests :-)
*/
private static RequestQueue mRequestQueue;
// ImageLoader Instance
private RequestManager() {
}
public static RequestManager get(Context context) {
if (mRequestManager == null)
mRequestManager = new RequestManager();
return mRequestManager;
}
/**
* #param context application context
*/
public static RequestQueue getnstance(Context context) {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(context);
}
return mRequestQueue;
}
}
3)Now Create a Class to handle Request for uploading File WebService
public class WebService {
private RequestQueue mRequestQueue;
private static WebService apiRequests = null;
public static WebService getInstance() {
if (apiRequests == null) {
apiRequests = new WebService();
return apiRequests;
}
return apiRequests;
}
public void updateProfile(Context context, String doc_name, String doc_type, String appliance_id, File file, Response.Listener<String> listener, Response.ErrorListener errorListener) {
SimpleMultiPartRequest request = new SimpleMultiPartRequest(Request.Method.POST, "YOUR URL HERE", listener, errorListener);
// request.setParams(data);
mRequestQueue = RequestManager.getnstance(context);
request.addMultipartParam("token", "text", "tdfysghfhsdfh");
request.addMultipartParam("parameter_1", "text", doc_name);
request.addMultipartParam("dparameter_2", "text", doc_type);
request.addMultipartParam("parameter_3", "text", appliance_id);
request.addFile("document_file", file.getPath());
request.setFixedStreamingMode(true);
mRequestQueue.add(request);
}
}
4) And Now Call The method Like This to Hit the service
public class Main2Activity extends AppCompatActivity implements Response.ErrorListener, Response.Listener<String>{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadData();
}
});
}
private void uploadData() {
WebService.getInstance().updateProfile(getActivity(), "appl_doc", "appliance", "1", mChoosenFile, this, this);
}
#Override
public void onErrorResponse(VolleyError error) {
}
#Override
public void onResponse(String response) {
//Your response here
}
}
This is my way of doing it. It may be useful to others :
private void updateType(){
// Log.i(TAG,"updateType");
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// running on main thread-------
try {
JSONObject res = new JSONObject(response);
res.getString("result");
System.out.println("Response:" + res.getString("result"));
}else{
CustomTast ct=new CustomTast(context);
ct.showCustomAlert("Network/Server Disconnected",R.drawable.disconnect);
}
} catch (Exception e) {
e.printStackTrace();
//Log.e("Response", "==> " + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
// running on main thread-------
VolleyLog.d(TAG, "Error: " + volleyError.getMessage());
}
}) {
protected Map<String, String> getParams() {
HashMap<String, String> hashMapParams = new HashMap<String, String>();
hashMapParams.put("key", "value");
hashMapParams.put("key", "value");
hashMapParams.put("key", "value"));
hashMapParams.put("key", "value");
System.out.println("Hashmap:" + hashMapParams);
return hashMapParams;
}
};
AppController.getInstance().addToRequestQueue(request);
}
Has anyone been able to accomplish sending a multipart/form-data POST in Android with Volley yet? I have had no success trying to upload an image/png using a POST request to our server and am curious if anyone has.
I believe the default way to do this would be to override public byte[] getPostBody() in the Request.java class and attach the File there with a blank Header key for the boundary. However, converting my file to a String for the Map<String, String> postParams and then having it encoded again seems obtuse and not really elegant. Also I've been unsuccessful in my attempts. This is really the only thing holding us back from switching to this library.
Anyway, all thoughts and answers are extremely appreciated. Thank you for your help.
I might be wrong on this but I think you need to implement your own com.android.volley.toolbox.HttpStack for this because the default ones (HurlStack if version > Gingerbread or HttpClientStack) don't deal with multipart/form-data.
Edit:
And indeed I was wrong. I was able to do it using MultipartEntity in Request like this:
public class MultipartRequest extends Request<String> {
private MultipartEntity entity = new MultipartEntity();
private static final String FILE_PART_NAME = "file";
private static final String STRING_PART_NAME = "text";
private final Response.Listener<String> mListener;
private final File mFilePart;
private final String mStringPart;
public MultipartRequest(String url, Response.ErrorListener errorListener, Response.Listener<String> listener, File file, String stringPart)
{
super(Method.POST, url, errorListener);
mListener = listener;
mFilePart = file;
mStringPart = stringPart;
buildMultipartEntity();
}
private void buildMultipartEntity()
{
entity.addPart(FILE_PART_NAME, new FileBody(mFilePart));
try
{
entity.addPart(STRING_PART_NAME, new StringBody(mStringPart));
}
catch (UnsupportedEncodingException e)
{
VolleyLog.e("UnsupportedEncodingException");
}
}
#Override
public String getBodyContentType()
{
return entity.getContentType().getValue();
}
#Override
public byte[] getBody() throws AuthFailureError
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try
{
entity.writeTo(bos);
}
catch (IOException e)
{
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response)
{
return Response.success("Uploaded", getCacheEntry());
}
#Override
protected void deliverResponse(String response)
{
mListener.onResponse(response);
}
}
It's pretty raw but I tried it with an image and a simple string and it works. The response is a placeholder, doesn't make much sense to return a Response String in this case. I had problems using apache httpmime to use MultipartEntity so I used this https://code.google.com/p/httpclientandroidlib/ don't know if there's a better way.
Hope it helps.
Edit
You can use httpmime without using httpclientandroidlib, the only dependency is httpcore.
As mentioned in the presentation at the I/O (about 4:05), Volley "is terrible" for large payloads. As I understand it that means not to use Volley for receiving/sending (big) files. Looking at the code it seems that it is not even designed to handle multipart form data (e.g. Request.java has getBodyContentType() with hardcoded "application/x-www-form-urlencoded"; HttpClientStack::createHttpRequest() can handle only byte[], etc...). Probably you will be able to create implementation that can handle multipart but If I were you I will just use HttpClient directly with MultipartEntity like:
HttpPost req = new HttpPost(composeTargetUrl());
MultipartEntity entity = new MultipartEntity();
entity.addPart(POST_IMAGE_VAR_NAME, new FileBody(toUpload));
try {
entity.addPart(POST_SESSION_VAR_NAME, new StringBody(uploadSessionId));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
req.setEntity(entity);
You may need newer HttpClient (i.e. not the built-in) or even better, use Volley with newer HttpClient
UPDATE 2015/08/26:
If you don't want to use deprecated HttpEntity, here is my working sample code (tested with ASP.Net WebAPI)
MultipartActivity.java
package com.example.volleyapp;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.Menu;
import android.view.MenuItem;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.example.volleyapp.BaseVolleyRequest;
import com.example.volleyapp.VolleySingleton;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public class MultipartActivity extends Activity {
final Context mContext = this;
String mimeType;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String boundary = "apiclient-" + System.currentTimeMillis();
String twoHyphens = "--";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1024 * 1024;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multipart);
Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.ic_action_file_attachment_light);
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
final byte[] bitmapData = byteArrayOutputStream.toByteArray();
String url = "http://192.168.1.100/api/postfile";
mimeType = "multipart/form-data;boundary=" + boundary;
BaseVolleyRequest baseVolleyRequest = new BaseVolleyRequest(1, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public String getBodyContentType() {
return mimeType;
}
#Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
dos = new DataOutputStream(bos);
try {
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ "ic_action_file_attachment_light.png" + "\"" + lineEnd);
dos.writeBytes(lineEnd);
ByteArrayInputStream fileInputStream = new ByteArrayInputStream(bitmapData);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return bitmapData;
}
};
VolleySingleton.getInstance(mContext).addToRequestQueue(baseVolleyRequest);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_multipart, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
BaseVolleyRequest.java:
package com.example.volleyapp;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.JsonSyntaxException;
public class BaseVolleyRequest extends Request<NetworkResponse> {
private final Response.Listener<NetworkResponse> mListener;
private final Response.ErrorListener mErrorListener;
public BaseVolleyRequest(String url, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
super(0, url, errorListener);
this.mListener = listener;
this.mErrorListener = errorListener;
}
public BaseVolleyRequest(int method, String url, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.mListener = listener;
this.mErrorListener = errorListener;
}
#Override
protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
try {
return Response.success(
response,
HttpHeaderParser.parseCacheHeaders(response));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
} catch (Exception e) {
return Response.error(new ParseError(e));
}
}
#Override
protected void deliverResponse(NetworkResponse response) {
mListener.onResponse(response);
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
return super.parseNetworkError(volleyError);
}
#Override
public void deliverError(VolleyError error) {
mErrorListener.onErrorResponse(error);
}
}
END OF UPDATE
This is my working sample code (only tested with small-size files):
public class FileUploadActivity extends Activity {
private final Context mContext = this;
HttpEntity httpEntity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file_upload);
Drawable drawable = getResources().getDrawable(R.drawable.ic_action_home);
if (drawable != null) {
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
final byte[] bitmapdata = stream.toByteArray();
String url = "http://10.0.2.2/api/fileupload";
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
// Add binary body
if (bitmapdata != null) {
ContentType contentType = ContentType.create("image/png");
String fileName = "ic_action_home.png";
builder.addBinaryBody("file", bitmapdata, contentType, fileName);
httpEntity = builder.build();
MyRequest myRequest = new MyRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
Toast.makeText(mContext, jsonString, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mContext, error.toString(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
public String getBodyContentType() {
return httpEntity.getContentType().getValue();
}
#Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
httpEntity.writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
};
MySingleton.getInstance(this).addToRequestQueue(myRequest);
}
}
}
...
}
public class MyRequest extends Request<NetworkResponse>
Complete Multipart Request with Upload Progress
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.util.CharsetUtils;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.beusoft.app.AppContext;
public class MultipartRequest extends Request<String> {
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
HttpEntity httpentity;
private String FILE_PART_NAME = "files";
private final Response.Listener<String> mListener;
private final File mFilePart;
private final Map<String, String> mStringPart;
private Map<String, String> headerParams;
private final MultipartProgressListener multipartProgressListener;
private long fileLength = 0L;
public MultipartRequest(String url, Response.ErrorListener errorListener,
Response.Listener<String> listener, File file, long fileLength,
Map<String, String> mStringPart,
final Map<String, String> headerParams, String partName,
MultipartProgressListener progLitener) {
super(Method.POST, url, errorListener);
this.mListener = listener;
this.mFilePart = file;
this.fileLength = fileLength;
this.mStringPart = mStringPart;
this.headerParams = headerParams;
this.FILE_PART_NAME = partName;
this.multipartProgressListener = progLitener;
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
try {
entity.setCharset(CharsetUtils.get("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
buildMultipartEntity();
httpentity = entity.build();
}
// public void addStringBody(String param, String value) {
// if (mStringPart != null) {
// mStringPart.put(param, value);
// }
// }
private void buildMultipartEntity() {
entity.addPart(FILE_PART_NAME, new FileBody(mFilePart, ContentType.create("image/gif"), mFilePart.getName()));
if (mStringPart != null) {
for (Map.Entry<String, String> entry : mStringPart.entrySet()) {
entity.addTextBody(entry.getKey(), entry.getValue());
}
}
}
#Override
public String getBodyContentType() {
return httpentity.getContentType().getValue();
}
#Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
httpentity.writeTo(new CountingOutputStream(bos, fileLength,
multipartProgressListener));
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
try {
// System.out.println("Network Response "+ new String(response.data, "UTF-8"));
return Response.success(new String(response.data, "UTF-8"),
getCacheEntry());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
// fuck it, it should never happen though
return Response.success(new String(response.data), getCacheEntry());
}
}
#Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
//Override getHeaders() if you want to put anything in header
public static interface MultipartProgressListener {
void transferred(long transfered, int progress);
}
public static class CountingOutputStream extends FilterOutputStream {
private final MultipartProgressListener progListener;
private long transferred;
private long fileLength;
public CountingOutputStream(final OutputStream out, long fileLength,
final MultipartProgressListener listener) {
super(out);
this.fileLength = fileLength;
this.progListener = listener;
this.transferred = 0;
}
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
if (progListener != null) {
this.transferred += len;
int prog = (int) (transferred * 100 / fileLength);
this.progListener.transferred(this.transferred, prog);
}
}
public void write(int b) throws IOException {
out.write(b);
if (progListener != null) {
this.transferred++;
int prog = (int) (transferred * 100 / fileLength);
this.progListener.transferred(this.transferred, prog);
}
}
}
}
Sample Usage
protected <T> void uploadFile(final String tag, final String url,
final File file, final String partName,
final Map<String, String> headerParams,
final Response.Listener<String> resultDelivery,
final Response.ErrorListener errorListener,
MultipartProgressListener progListener) {
AZNetworkRetryPolicy retryPolicy = new AZNetworkRetryPolicy();
MultipartRequest mr = new MultipartRequest(url, errorListener,
resultDelivery, file, file.length(), null, headerParams,
partName, progListener);
mr.setRetryPolicy(retryPolicy);
mr.setTag(tag);
Volley.newRequestQueue(this).add(mr);
}
A very simple approach for the dev who just want to send POST parameters in multipart request.
Make the following changes in class which extends Request.java
First define these constants :
String BOUNDARY = "s2retfgsGSRFsERFGHfgdfgw734yhFHW567TYHSrf4yarg"; //This the boundary which is used by the server to split the post parameters.
String MULTIPART_FORMDATA = "multipart/form-data;boundary=" + BOUNDARY;
Add a helper function to create a post body for you :
private String createPostBody(Map<String, String> params) {
StringBuilder sbPost = new StringBuilder();
if (params != null) {
for (String key : params.keySet()) {
if (params.get(key) != null) {
sbPost.append("\r\n" + "--" + BOUNDARY + "\r\n");
sbPost.append("Content-Disposition: form-data; name=\"" + key + "\"" + "\r\n\r\n");
sbPost.append(params.get(key).toString());
}
}
}
return sbPost.toString();
}
Override getBody() and getBodyContentType
public String getBodyContentType() {
return MULTIPART_FORMDATA;
}
public byte[] getBody() throws AuthFailureError {
return createPostBody(getParams()).getBytes();
}
First answer on SO.
I have encountered the same problem and found #alex 's code very helpful. I have made some simple modifications in order to pass in as many parameters as needed through HashMap, and have basically copied parseNetworkResponse() from StringRequest. I have searched online and so surprised to find out that such a common task is so rarely answered. Anyway, I wish the code could help:
public class MultipartRequest extends Request<String> {
private MultipartEntity entity = new MultipartEntity();
private static final String FILE_PART_NAME = "image";
private final Response.Listener<String> mListener;
private final File file;
private final HashMap<String, String> params;
public MultipartRequest(String url, Response.Listener<String> listener, Response.ErrorListener errorListener, File file, HashMap<String, String> params)
{
super(Method.POST, url, errorListener);
mListener = listener;
this.file = file;
this.params = params;
buildMultipartEntity();
}
private void buildMultipartEntity()
{
entity.addPart(FILE_PART_NAME, new FileBody(file));
try
{
for ( String key : params.keySet() ) {
entity.addPart(key, new StringBody(params.get(key)));
}
}
catch (UnsupportedEncodingException e)
{
VolleyLog.e("UnsupportedEncodingException");
}
}
#Override
public String getBodyContentType()
{
return entity.getContentType().getValue();
}
#Override
public byte[] getBody() throws AuthFailureError
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try
{
entity.writeTo(bos);
}
catch (IOException e)
{
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
/**
* copied from Android StringRequest class
*/
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
#Override
protected void deliverResponse(String response)
{
mListener.onResponse(response);
}
And you may use the class as following:
HashMap<String, String> params = new HashMap<String, String>();
params.put("type", "Some Param");
params.put("location", "Some Param");
params.put("contact", "Some Param");
MultipartRequest mr = new MultipartRequest(url, new Response.Listener<String>(){
#Override
public void onResponse(String response) {
Log.d("response", response);
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley Request Error", error.getLocalizedMessage());
}
}, f, params);
Volley.newRequestQueue(this).add(mr);
Another solution, very light with high performance with payload large:
Android Asynchronous Http Client library:
http://loopj.com/android-async-http/
private static AsyncHttpClient client = new AsyncHttpClient();
private void uploadFileExecute(File file) {
RequestParams params = new RequestParams();
try { params.put("photo", file); } catch (FileNotFoundException e) {}
client.post(getUrl(), params,
new AsyncHttpResponseHandler() {
public void onSuccess(String result) {
Log.d(TAG,"uploadFile response: "+result);
};
public void onFailure(Throwable arg0, String errorMsg) {
Log.d(TAG,"uploadFile ERROR!");
};
}
);
}
Here is Simple Solution And Complete Example for Uploading File Using Volley Android
1) Gradle Import
compile 'dev.dworks.libs:volleyplus:+'
2)Now Create a Class RequestManager
public class RequestManager {
private static RequestManager mRequestManager;
/**
* Queue which Manages the Network Requests :-)
*/
private static RequestQueue mRequestQueue;
// ImageLoader Instance
private RequestManager() {
}
public static RequestManager get(Context context) {
if (mRequestManager == null)
mRequestManager = new RequestManager();
return mRequestManager;
}
/**
* #param context application context
*/
public static RequestQueue getnstance(Context context) {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(context);
}
return mRequestQueue;
}
}
3)Now Create a Class to handle Request for uploading File WebService
public class WebService {
private RequestQueue mRequestQueue;
private static WebService apiRequests = null;
public static WebService getInstance() {
if (apiRequests == null) {
apiRequests = new WebService();
return apiRequests;
}
return apiRequests;
}
public void updateProfile(Context context, String doc_name, String doc_type, String appliance_id, File file, Response.Listener<String> listener, Response.ErrorListener errorListener) {
SimpleMultiPartRequest request = new SimpleMultiPartRequest(Request.Method.POST, "YOUR URL HERE", listener, errorListener);
// request.setParams(data);
mRequestQueue = RequestManager.getnstance(context);
request.addMultipartParam("token", "text", "tdfysghfhsdfh");
request.addMultipartParam("parameter_1", "text", doc_name);
request.addMultipartParam("dparameter_2", "text", doc_type);
request.addMultipartParam("parameter_3", "text", appliance_id);
request.addFile("document_file", file.getPath());
request.setFixedStreamingMode(true);
mRequestQueue.add(request);
}
}
4) And Now Call The method Like This to Hit the service
public class Main2Activity extends AppCompatActivity implements Response.ErrorListener, Response.Listener<String>{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadData();
}
});
}
private void uploadData() {
WebService.getInstance().updateProfile(getActivity(), "appl_doc", "appliance", "1", mChoosenFile, this, this);
}
#Override
public void onErrorResponse(VolleyError error) {
}
#Override
public void onResponse(String response) {
//Your response here
}
}
This is my way of doing it. It may be useful to others :
private void updateType(){
// Log.i(TAG,"updateType");
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// running on main thread-------
try {
JSONObject res = new JSONObject(response);
res.getString("result");
System.out.println("Response:" + res.getString("result"));
}else{
CustomTast ct=new CustomTast(context);
ct.showCustomAlert("Network/Server Disconnected",R.drawable.disconnect);
}
} catch (Exception e) {
e.printStackTrace();
//Log.e("Response", "==> " + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
// running on main thread-------
VolleyLog.d(TAG, "Error: " + volleyError.getMessage());
}
}) {
protected Map<String, String> getParams() {
HashMap<String, String> hashMapParams = new HashMap<String, String>();
hashMapParams.put("key", "value");
hashMapParams.put("key", "value");
hashMapParams.put("key", "value"));
hashMapParams.put("key", "value");
System.out.println("Hashmap:" + hashMapParams);
return hashMapParams;
}
};
AppController.getInstance().addToRequestQueue(request);
}