Android: Upload image or file using http POST multi-part


Hi,

After spending whole day, I thought that I should post my experience.

I’m trying to upload image to my server using Android 1.5 SDK.

By using this method,  you will be able to upload a file from your SD Card and also Bitmap image as a file.

Prerequisite: httpmime-4.1-beta1.jar

Android SDK uses apache  http Client of version 3.0. That does not support for the mime type.

So download the latest HttpClient from here. (Go to latest i.e. HttpClient 4.1-Beta1, and download zip file from Binary with dependencies)

Now include the above jar file as an external jar file.

Now create a new project and update your code from following:

package com.isummation.fileupload;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;

public class FileUpload extends Activity {
	Bitmap bm;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		try {
			// bm = BitmapFactory.decodeResource(getResources(),
			// R.drawable.forest);
			bm = BitmapFactory.decodeFile("/sdcard/DCIM/forest.png");
			executeMultipartPost();
		} catch (Exception e) {
			Log.e(e.getClass().getName(), e.getMessage());
		}
	}

	public void executeMultipartPost() throws Exception {
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			bm.compress(CompressFormat.JPEG, 75, bos);
			byte[] data = bos.toByteArray();
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost postRequest = new HttpPost(
					"http://10.0.2.2/cfc/iphoneWebservice.cfc?returnformat=json&method=testUpload");
			ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg");
			// File file= new File("/mnt/sdcard/forest.png");
			// FileBody bin = new FileBody(file);
			MultipartEntity reqEntity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			reqEntity.addPart("uploaded", bab);
			reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf"));
			postRequest.setEntity(reqEntity);
			HttpResponse response = httpClient.execute(postRequest);
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent(), "UTF-8"));
			String sResponse;
			StringBuilder s = new StringBuilder();

			while ((sResponse = reader.readLine()) != null) {
				s = s.append(sResponse);
			}
			System.out.println("Response: " + s);
		} catch (Exception e) {
			// handle exception here
			Log.e(e.getClass().getName(), e.getMessage());
		}
	}
}

Modify web service URL to match yours.

Also note that I commented some lines in executeMultipartPost() method. This is used to read a file from SD card, then pass this bin object in reqEntity.addPart() method to upload any file.

FYI: png formatted file and Bitmap images are too big. So I compress it to JPEG format while uploading.

See the line:

bm.compress(CompressFormat.JPEG, 75, bos);

This is very important, because it can convert a 1.8 MB file to 180 KB!.

PS: In example, I’m using ColdFusion component (cfc) as a Restful service with JSON as return format. This is the easiest way to implement your server part. I am also using Android 1.5 SDK, because I believe that your application should be compatible with all ( varying from 1.5 to 2.3) SDK versions!.

Hope that this post helps you…

You might also like: https://vikaskanani.wordpress.com/2011/01/29/android-image-upload-activity/

About these ads

143 thoughts on “Android: Upload image or file using http POST multi-part

  1. William

    Thanks.

    But there is a problem. I have a web service which expects detailed images, if I send compressed image, it is useless.

    I want to be able to send a picture which is 5 mb for example. How can I do that?

    Reply
      1. Guruprasad Bhavsar

        if u put ZERO as parameter thn it defrming d image completely….
        if u dnt want to compress (in other words with much less loses) use 100 as parameter…
        as
        bm.compress(CompressFormat.JPEG, 100, bos);

  2. Vinothkumar Arputharaj

    Getting Nullpointerexception while running this code.

    Help me please.


    package my.trail.upload;

    import java.io.BufferedReader;
    import java.io.ByteArrayOutputStream;
    import java.io.InputStreamReader;

    import org.apache.http.HttpHost;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.conn.params.ConnRoutePNames;
    import org.apache.http.entity.mime.HttpMultipartMode;
    import org.apache.http.entity.mime.MultipartEntity;
    import org.apache.http.entity.mime.content.ByteArrayBody;
    import org.apache.http.entity.mime.content.StringBody;
    import org.apache.http.impl.client.DefaultHttpClient;

    import android.app.Activity;
    import android.graphics.Bitmap;
    import android.graphics.Bitmap.CompressFormat;
    import android.graphics.BitmapFactory;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.TextView;
    import android.widget.Toast;

    public class FileUploadActivity extends Activity {

    TextView tv;
    Bitmap bm;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    try {
    // bm = BitmapFactory.decodeResource(getResources(),
    // R.drawable.forest);
    bm = BitmapFactory.decodeFile("file:///mnt/sdcard/DCIM/letter.jpg");
    findViewById(R.id.Button01).setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

    try {
    executeMultipartPost(bm);
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    tv = (TextView) findViewById(R.id.txt);
    tv.setText("Err: "+e.getStackTrace().toString());
    }
    }
    });

    } catch (Exception e) {
    Log.e(e.getClass().getName(), e.getMessage());
    tv = (TextView) findViewById(R.id.txt);
    tv.setText("Err1: "+e.getStackTrace().toString());
    }

    }

    public void executeMultipartPost(Bitmap bm) throws Exception {
    try {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bm.compress(CompressFormat.JPEG, 0, bos);
    byte[] data = bos.toByteArray();

    String myKey = "key";

    String url = "http://ws.webservius.com/sts/v1/20mb/15m?wsvKey="+myKey+"&extension=jpg";

    HttpClient httpClient = new DefaultHttpClient();
    HttpHost proxy = new HttpHost("host", 8000);
    httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);

    HttpPost postRequest = new HttpPost(url);
    postRequest.setHeader("Content-Type","text/xml");

    ByteArrayBody bab = new ByteArrayBody(data, "letter.jpg");
    // File file= new File("/mnt/sdcard/forest.png");
    // FileBody bin = new FileBody(file);

    MultipartEntity reqEntity = new MultipartEntity(
    HttpMultipartMode.BROWSER_COMPATIBLE);
    reqEntity.addPart("uploaded", bab);
    reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf"));

    postRequest.setEntity(reqEntity);

    HttpResponse response = httpClient.execute(postRequest);

    BufferedReader reader = new BufferedReader(new InputStreamReader(
    response.getEntity().getContent(), "UTF-8"));
    String sResponse;
    StringBuilder s = new StringBuilder();

    while ((sResponse = reader.readLine()) != null) {
    s = s.append(sResponse);
    }
    Toast.makeText(FileUploadActivity.this, "Res : "+s.toString(), Toast.LENGTH_LONG).show();
    System.out.println("Response: " + s);
    } catch (Exception e) {
    // handle exception here
    e.printStackTrace();
    Log.e(e.getClass().getName(), e.getMessage());
    setContentView(R.layout.main);
    tv = (TextView) findViewById(R.id.txt);
    tv.setText("Final Err: "+e.getStackTrace().toString());
    }
    }
    }

    I’m getting NullPointerException in the lines 70 & 110.

    Help me to solve this. Please.

    My Site

    Reply
  3. g robert

    Hey this is working great. My only problem is that when I attempt to upload a second image, the program lock and I must choose force close. After force close, the program is able to upload again. I am using the code as exactly you instructed. Any ideas why this is happening?

    Reply
  4. Hikaru

    do you know if I can send an image to a webservice using soap? I capture an image with a built in camera then send it and a method should generate an aleatory number from 1 to 8. Do you know if sending images using soap is possible?

    Reply
    1. Vikas Post author

      Have you tried this?
      File file= new File(“/mnt/sdcard/forest.png”);
      FileBody bin = new FileBody(file);

      I think it would work, didn’t tested.

      Reply
  5. Pingback: cho hỏi về cách upload hình lên webservice

  6. ied

    i need help :
    how can i upload a image
    there is no error, when i click to upload didn’t do anything
    just write “please select image”
    so how i select the image
    ????

    Reply
      1. hazel

        hello.. what set up menu you mean?? would appreciate if you could elaborate further? or give example. thank you ;)

      2. newuser

        Hi Vikas,
        I want to upload image from inBuilt gallery, i don’t have menu button set up as u have stated to “ied” , when i click on “menu” from keypad and Gallery appear with “no media found” in gallery.
        i will try setting up menu button ,
        any help will be highly Appriciated,
        newuser.

  7. subrahmanya

    package com.example.multipartpost;

    import java.io.BufferedInputStream;
    import java.io.BufferedReader;
    import java.io.ByteArrayInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.InetAddress;
    import java.net.URI;
    import java.net.UnknownHostException;
    import java.util.ArrayList;
    import java.util.List;

    import org.apache.http.HttpResponse;
    import org.apache.http.auth.AuthScope;
    import org.apache.http.auth.NTCredentials;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.CredentialsProvider;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.ByteArrayEntity;
    import org.apache.http.entity.mime.MultipartEntity;
    import org.apache.http.entity.mime.content.InputStreamBody;
    import org.apache.http.entity.mime.content.StringBody;
    import org.apache.http.impl.client.BasicCredentialsProvider;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.protocol.BasicHttpContext;
    import org.apache.http.protocol.HttpContext;
    import org.ksoap2.HeaderProperty;
    import org.ksoap2.SoapEnvelope;
    import org.ksoap2.serialization.PropertyInfo;
    import org.ksoap2.serialization.SoapObject;
    import org.ksoap2.serialization.SoapSerializationEnvelope;
    import org.ksoap2.transport.HttpTransportSE;
    import org.xmlpull.v1.XmlPullParserException;

    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.os.AsyncTask;
    import android.os.Bundle;
    public class MultiPartPost extends Activity
    {
    private ProgressDialog pd;
    String cookie= “”;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    try {
    new Task().execute();

    } catch (Exception e) {
    // TODO Auto-generated catch block
    System.out.println(“In OnCreateMethod Exception from ExecuteMultiPart “);
    e.printStackTrace();
    }
    }

    public void executeMultipartPost(String cookie)throws Exception
    {
    InputStream is = null;
    try {
    byte[] fileContent = xmlStr.getBytes();
    File file = new File(“/sdcard”,”abcdefgh.xml”);
    try {
    is = new BufferedInputStream(new FileInputStream(file));

    } catch(IOException e)
    {
    e.printStackTrace();

    }
    //is = this.getAssets().open(“data.xml”);
    HttpClient httpClient = new DefaultHttpClient();

    HttpPost postRequest = new HttpPost(“http://182.71.118.242:3000/_vti_bin/listdata.svc/SharedDocuments”);
    postRequest.addHeader(“Cookie”, cookie);
    postRequest.addHeader(“Slug”,”/abcdefgh.xml”);
    postRequest.addHeader(“Content-Type”,”application/atom+xml”);

    postRequest.addHeader(“User-Agent”, “Android/2.2″);

    postRequest.addHeader(“Cache-Control”, “no-cache”);
    postRequest.setEntity(new ByteArrayEntity(fileContent));

    String str=is.toString();
    byte[] data = str.getBytes();
    //byte[] data = IOUtils.toByteArray(is);
    InputStreamBody isb = new InputStreamBody(new ByteArrayInputStream(data),”abcdefgh.xml”);
    //StringBody sb1 = new StringBody(“someTextGoesHere”);
    //StringBody sb2 = new StringBody(“someTextGoesHere too”);
    MultipartEntity multipartContent = new MultipartEntity();
    multipartContent.addPart(“abcdefgh.xml”, isb);
    //multipartContent.addPart(“one”, sb1);
    //multipartContent.addPart(“two”, sb2);
    postRequest.setEntity(multipartContent);
    HttpResponse response = httpClient.execute(postRequest);
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    response.getEntity().getContent(), “UTF-8″));
    System.out.println(“Status code:” +response.getStatusLine().getStatusCode());
    String sResponse;
    StringBuilder s = new StringBuilder();

    while ((sResponse = reader.readLine()) != null) {
    s = s.append(sResponse);
    }
    System.out.println(“Response: ” + s);

    //response.getEntity().getContent().close();
    } catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    System.out.println(“protocol Exception”);
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

    class Task extends AsyncTask {

    @Override
    protected Void doInBackground(Void… params) {
    // TODO Auto-generated method stub
    // login properties
    SoapObject loginRequest = new SoapObject(“http://schemas.microsoft.com/sharepoint/soap/”,
    “Login”);

    PropertyInfo pi = new PropertyInfo();
    pi.setName(“username”);
    pi.setValue(“india\\sp-moss-accnt”);
    pi.setType(String.class);
    loginRequest.addProperty(pi);

    PropertyInfo pi2 = new PropertyInfo();
    pi2.setName(“password”);
    pi2.setValue(“Password1!”);
    pi2.setType(String.class);
    loginRequest.addProperty(pi2);
    // loginTrasnport
    HttpTransportSE loginTransport = new HttpTransportSE(
    “http://182.71.118.242:3000/_vti_bin/Authentication.asmx”);
    loginTransport.debug = true;
    loginTransport
    .setXmlVersionTag(“”);
    SoapSerializationEnvelope loginEnvelope = new
    SoapSerializationEnvelope(
    SoapEnvelope.VER11);
    loginEnvelope.dotNet = true;
    loginEnvelope.encodingStyle = SoapSerializationEnvelope.ENC;
    loginEnvelope.setOutputSoapObject(loginRequest);
    // login headers
    List loginHdPropertieList = new
    ArrayList();
    loginHdPropertieList.add(new HeaderProperty(“Host”,
    “182.71.118.242″));
    loginHdPropertieList.add(new HeaderProperty(“Content-Type”,
    “text/xml; charset=utf-8″));
    loginHdPropertieList.add(new HeaderProperty(“Cookie”, “”));
    System.out.println(“Before login response”);
    // login response
    List loginHeaders=null;
    try {
    loginHeaders = loginTransport.call(
    “http://schemas.microsoft.com/sharepoint/soap/Login”, loginEnvelope,
    loginHdPropertieList);
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (XmlPullParserException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    System.out.println(“Before Catching response”);
    // String cookie=””;
    if (loginHeaders != null) {
    for (int ix = 0; ix < loginHeaders.size(); ix++) {
    HeaderProperty hp = (HeaderProperty) loginHeaders.get(ix);

    if ("set-cookie".equalsIgnoreCase(hp.getKey())) {
    cookie = hp.getValue();
    System.out.println("Cookie value = " + cookie);
    }
    }
    }

    try {
    executeMultipartPost(cookie);
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    return null;
    }

    @Override
    protected void onPreExecute() {
    pd = ProgressDialog.show(MultiPartPost.this, "test", "mesage");
    }

    protected void onPostExecute(Void t) {

    pd.dismiss();

    }

    }
    String xmlStr = new String("” +

    “” +

    “” +
    “” +
    “” +

    “” +

    “” +
    “1″ +
    “0x010100260CAD01D5FE7B49B785EE10A956A14F” +

    “/Shared Documents” +

    “abcdefgh.xml” +
    “1.0″ +
    “” +
    “”);
    }

    abcdef.xml is present in my /sdcard folder. iam trying to upload the abcdef.xml file into the server. But the server is throwing error status code: 500 and it is failing to upload.

    Could any one please help me out.

    Reply
  8. Subrahmanya

    Hi Vikas Thanks for your reply. But the same code is working if i use ksoap.
    Do i need to add any extra headers.

    Reply
  9. Subrahmanya

    reqEntity.addPart(“photoCaption”, new StringBody(“sfsdfsdf”));

    In the intial code you have used the above line? what is the importance of this ? Can we give any name String for the first parameter. Is this line have any importance ? will it work if we skip this line. ?

    Reply
  10. Subrahmanya

    FileBody fiebody = new FileBody(new file(“/sdcard”,”abcdefgh.xml”));
    HttpPost postRequest = new HttpPost(“http://182.71.118.242:3000/_vti_bin/listdata.svc/SharedDocuments”);
    postRequest.addHeader(“Cookie”, cookie);
    postRequest.addHeader(“Slug”,”/abcdefgh.xml”);
    postRequest.addHeader(“Content-Type”,”multipart/form-data”);
    postRequest.addHeader(“User-Agent”, “Android/2.2″);
    postRequest.addHeader(“Cache-Control”, “no-cache”);

    MultipartEntity multipartContent = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    multipartContent.addPart(“abcdefgh.xml”, filebody);
    postRequest.setEntity(multipartContent);

    HttpResponse response = httpClient.execute(postRequest);

    BufferedReader reader = new BufferedReader(new InputStreamReader(
    response.getEntity().getContent(), “UTF-8″));
    System.out.println(“Status code:” +response.getStatusLine().getStatusCode());

    I have stored abcdefgh.xml file in my /sdcard folder.
    The response code iam getting as 500. Could you please once check and tell if there is any mistake in my code ?

    Reply
    1. Vikas Post author

      I again tell you, there is no error from android side, you should check your web service or url, and test it by using browser form post method, status code 500 means server side error.

      Reply
  11. Subrahmanya

    Hi ,
    The problem is with slug header.We should provide complete path.
    i.e We should use postRequest.addHeader(“Slug”,”http://182.71.118.242:3000/Shared%20Documents/abcdefgh.xml”);
    instead of postRequest.addHeader(“Slug”,”/abcdefgh.xml”);

    And many thanks for your suggestions and quick response :)…

    Reply
  12. RR

    Hi

    Thanks for your samples, and I would like to ask what if I have to upload 2 more files at same time?
    For example, there is a html page like this:

    Normally, user used their browser to visit this page, and select 2 files to upload.
    What should I do through android client ?

    Reply
      1. RR

        Thanks for your answer, but unfortunaty my client is android platform, and some apache http client just not working on……:-(

        Still thanks for your help :-)

  13. Pradeep VR

    Hi I am not able to create StringBody, FileBody, ContentBody, InputStreamBody objects, eclipse is showing compile time error:
    The type org.apache.james.mime4j.message.TextBody cannot be resolved. It is indirectly referenced from required .class files

    I tried to configure my build path but could not succeed, can u please tell me how to configure my build path along with android.jar.

    And my httpmime-4.0-beta1.jar doesnot contain ByteArrayBody.class, where can i get that?

    Thnx in advance.

    Reply
  14. Ceiling

    Thank you for any other informative blog. Where else could I am getting that type of info written in such a perfect approach? I’ve a project that I am simply now working on, and I’ve been on the look out for such info.

    Reply
  15. subrah

    How to create a folder in sharepoint library using REST Api’s? could any body help me out please.

    Below is my request xml and sample code which i used.

    String reqXmlBody = new String(
    “”
    +”MyFolder”
    + “”
    + “”
    +”MyFolder”
    +”Folder”
    + “”
    + “”);
    HttpClient httpClient = null;
    HttpPost postReq = new HttpPost(“http://10.34.52.9:3000/_vti_bin/Listdata.svc/DocLib”);
    String cookie = getCookie()// this method will get the current cookie.
    postReq.addHeader(“Cookie”,cookie));
    postReq.addHeader(“Content-Type”,”application/atom+xml”);
    postReq.addHeader(“Slug”,”http://10.34.52.9:3000/”);
    postReq.addHeader(“User-Agent”,”text/application”);
    postReq.setEntity(new StringEntity(reqXmlBody));
    HttpResponse response = httpClient.execute(postReq, context);//your applicaton context.

    The above code is always throwing the below error.

    Bad Request

    Bad Request – Invalid Header
    HTTP Error 400. The request has an invalid header name.

    as reponse.i tried with HttpPut as well.

    Reply
  16. ben

    Don’t you lose you exif data on the load and recompress back to jpeg? I’ve been trying to upload images a dozen ways and the problem (other than using FTP) is always that the traditional method of loading into a decoded bitmap and recompressing back to jpeg to conserve space loses the exif data. ?

    Reply
  17. Pradeep VR

    Hi All, I am getting the below error:

    The type org.apache.james.mime4j.message.TextBody cannot be resolved. It is indirectly referenced from required .class files.
    1 quick fix available:
    configure build path.

    Thnx in advance.

    Reply
  18. Pradeep VR

    Hi all, i am getting the below error and not able to compile the code:

    “The project was not built since its build path is incomplete. Cannot find the class file for org.apache.james.mime4j.message.BinaryBody. Fix the build path then try building this project.”

    But I have the jar in build path.
    Below is my code :
    1. FileBody bin = new FileBody(file);
    2. MultipartEntity reqEntity = new MultipartEntity(
    HttpMultipartMode.BROWSER_COMPATIBLE);
    3. reqEntity.addPart(“imagefile”, bin);
    i am getting the above error at line 3.

    Thnx in advance.

    Reply
      1. Pradeep VR

        Hi thnx for the code, I just downloaded it and brought up onto my eclipse, but even ur code is showing the same error :(
        for all the below lines of code :

        entity.addPart(“returnformat”, new StringBody(“json”));
        entity.addPart(“uploaded”, new ByteArrayBody(data,
        “myImage.jpg”));
        entity.addPart(“photoCaption”, new StringBody(caption.getText()
        .toString()));

      2. Pradeep VR

        Hi vikas issue have been fixed finally after using httpmime-4.1.2.jar. Earlier i was using httpmime-4.1-beta.jar. I think this beta jar was the reason for that issue. Thnx for this post.

  19. Doug Zumbrun

    This is very helpful, Vikas, thanks a lot.
    I need to be able to create php code that will take the image and insert it into a mysql database. I have code that will insert an image into a mysql database through a form uploaded from the pc, but can’t seem to figure out how to get the image from this post.

    Thanks

    Doug

    Reply
  20. Matt Huggins

    Just want to leave a HUGE thank you for your help here! This is what I’ve been searching for, and I got Android photo capture via camera + photo uploading to my server working in a matter of about 2 hours! :)

    Reply
  21. Pingback: Credit Where Credit Is Due

  22. John

    Hey, Vikas.
    Im using this code, it sents post data, but it sents it as application/octec stream not as image/*, sow what im doing wrong? Or is it intended to do so? On the server side i do print_r($_FILES) and all is showing up as application/octec.

    Reply
    1. phil

      Did you find an answer to this question, I have been stuck on it for two weeks now, its the only uploading image class i can get working and it uploads as a application/octet type ;( any ideas why its not sending as jpeg type anyone please??

      Reply
  23. Pradeep VR

    Hi Vikas, the client code for multi-part uploading the image seems to be working fine. But from the server side am not able to retrieve the image, can u tell me how to extract the image in server side. Below is my client code:

    HttpPost httpPost = new HttpPost(new URI(url));
    MultipartEntity reqEntity = new MultipartEntity(
    HttpMultipartMode.BROWSER_COMPATIBLE);

    // upload community image here
    if(mImagePath != null) {
    File file= new File(mImagePath);
    if(file.exists()) {
    reqEntity.addPart(“image”, new FileBody(file));
    }
    }
    httpPost.setEntity(reqEntity);

    Thnx in advance………

    Reply
  24. Bala

    Hi I have wriiten a application which uploads mutiple video files to a server . I used HTTP post method and multipart entity to do this..

    I need to implement this logic, say when i upload 5 files , while uploadin 4th file i get a network error. the next time i need to resume the upload to the 4th file, Any idea how can i implement this..

    Thanks
    Bala

    Reply
  25. Abhishek

    Hello thanks for the code But there is 1 problem. How to retrieve images the path u have given wont be remain same. I’m working on same application I want to upload captured image from the camera. This path u have mention in your code “/sdcard/DCIM/forest.png”. When I google I found that Different devices having different file path:

    That is Nexus-One stores its Camera files in to folder named “Camera” (/sdcard/DCIM/Camera).

    All HTC devices stores its camera files into a folder named “100MEDIA” (/sdcard/DCIM/100MEDIA).

    Sony Xperia x10 stores its camera files into folder named “100ANDRO” (/sdcard/DCIM/100ANDRO).

    Motorola MilesStone stores its camera files into folder named “Camera” (/sdcard/DCIM/Camera).

    How to make this application to run on all devices

    Reply
    1. Vikas Post author

      I am focusing on image uploading part here. This is why I hard coded the image path. You may use you gallery app to get actual physical path. See my other posts.

      Reply
  26. Matt

    Since i spent several days trying to figure out why this wasn’t working for me…

    This doesn’t work right in honeycomb initially:
    http://stackoverflow.com/questions/6277584/android-honeycomb-networkonmainthreadexception-even-when-using-asynctask-and-no

    You need:
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    To allow your main thread to run network tasks. I think there is a more elgant work around to put this into its own thread or something but unfortunately i don’t have time to figure that out.

    Reply
  27. Girish

    How to add an image to twitters using Oauth from android application.i’m able to send tweets but how to add an image as that of twitters tweet box.please give some hints

    Reply
  28. Jame Nguyen

    Dear,
    I’m using C# to handler upload on server side.
    Server code is:

    public partial class Save : System.Web.UI.Page {
    protected void Page_Load(object sender, EventArgs e) {
    if (Request.InputStream.Length > 0) {
    string sId = Request.QueryString["idl"]; //GET PARAM IDL FROM URL; ex. save.aspx?idl=56
    string saveTo = MapPath(“~”) + @”\IMG\img_” + sId + “_” + DateTime.Now.Ticks.ToString() + “.jpg”;

    FileStream writeStream = new FileStream(saveTo, FileMode.Create, FileAccess.Write);
    int Length = 256;
    Byte[] buffer = new Byte[Length];
    int bytesRead = Request.InputStream.Read(buffer, 0, Length);
    while (bytesRead > 0) {
    writeStream.Write(buffer, 0, bytesRead);
    bytesRead = Request.InputStream.Read(buffer, 0, Length);
    }
    Request.InputStream.Close();
    writeStream.Close();
    }
    }
    }

    But when upload file, i found an error image on server.

    Best regards,
    Jame Nguyen

    Reply
  29. Pingback: POSTing image from Android to WCF Rest Service | Software development support, software risk,bugs for bugs, risk analysis,

  30. lmichael (@lmichael)

    if you wanto upload original file by HttpClient
    public static String executeMultipart(String url, byte[] data,String fileField,String filename, HashMap params){
    String jsonString = null;
    try {
    HttpClient httpClient = getHttpClient(Constant.CLOUD_CONNECTION_TIMEOUT,Constant.CLOUD_SOCKET_TIMEOUT,”API”,mClient);
    HttpPost postRequest = new HttpPost(url);
    postRequest.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
    int count = filename.lastIndexOf(“/”);
    String fullFilename = filename;
    if (count != -1)
    filename = filename.substring(count + 1);

    String mimeType = “”;
    if (filename.endsWith(“.pdf”)) {
    mimeType = “application/pdf”;
    }
    else if (filename.endsWith(“.rtf”)) {
    mimeType = “application/rtf”;
    }
    else{
    mimeType = MediaFile.getMimetype(filename);
    }
    MultipartEntity multipartContent = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    if(data==null){
    multipartContent.addPart(fileField, new InputStreamBody(new FileInputStream(fullFilename), filename));
    }else{
    ByteArrayBody babFile = new ByteArrayBody(data,
    mimeType, filename);
    multipartContent.addPart(fileField, babFile);
    }
    Iterator iter = params.keySet().iterator();
    String key = “”;
    String value = “”;
    while(iter.hasNext()){
    key = iter.next();
    value = params.get(key);
    if(value!=null && !value.equals(“”)){
    multipartContent.addPart(key, new StringBody(value));
    }
    }
    postRequest.setEntity(multipartContent);
    HttpResponse res = httpClient.execute(postRequest);
    int statusCode = res.getStatusLine().getStatusCode();
    if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_MOVED_TEMPORARILY ){
    Log.d(TAG,”statusCode:”+statusCode);
    boolean isGzip = false;
    HttpEntity entity = res.getEntity();
    Header ceheader = entity.getContentEncoding();
    if (ceheader != null) {
    HeaderElement[] codecs = ceheader.getElements();
    for (int i = 0; i < codecs.length; i++) {
    if (codecs[i].getName().equalsIgnoreCase(ENCODING_GZIP)) {
    isGzip = true;
    break;
    }
    }
    }
    BufferedReader reader = new BufferedReader(
    new InputStreamReader(
    isGzip?new GZIPInputStream(entity.getContent()):entity.getContent(), "UTF-8"));
    StringBuilder builder = new StringBuilder(1024);
    for (String line = null; (line = reader.readLine()) != null;) {
    builder.append(line).append("\n");
    }
    jsonString = builder.toString();
    Log.d(TAG,"jsonString:"+jsonString);
    }
    } catch (MalformedURLException e) {
    e.printStackTrace();
    }catch (ConnectTimeoutException e) {
    e.printStackTrace();
    jsonString = "ConnectTimeoutException";
    }catch (IOException e) {
    e.printStackTrace();
    }
    return jsonString;
    }

    Reply
  31. subrahmanya

    Hi Vikas,
    I want to upload a document using HttpPost.
    Iam confused on which url i need to hit the server.

    my sharepoint server is http://10.9.42.9:4000. And i want to upload a document to location http://10.9.42.9:4000/MyDocumentLibrary.

    HttpPost postRequest = new HttpPost(“http://10.9.42.9:4000/MyDocumentLibrary”);
    so can i use directly the above url like this ? or
    HttpPost postRequest = new HttpPost(“http://10.9.42.9:4000/_vit_bin/listData.svc/MyDocumentLibrary”);
    should i hit the above url and send the location( http://10.9.42.9:4000/MyDocumentLibrary) where i need to upload as slug header?

    Reply
  32. predeep

    hi… i have error in import org.apache.http.entity.mime.HttpMultipartMode;
    import org.apache.http.entity.mime.MultipartEntity;
    import org.apache.http.entity.mime.content.ByteArrayBody;
    import org.apache.http.entity.mime.content.StringBody;

    i have downloaded jar file but i don’t know where to add it in eclipse

    Reply
  33. Marek Sebera

    Hi, I’ve used your sample with no problems. Thanks anyway for publishing it. There is too little of good HttpMime implementations examples.

    I’m in related trouble, maybe if you’d get an idea about solving it.

    I need to write to raw php input (raw body, no key). So that I can read it in PHP with `php://stdin`

    If I use MultipartEntity, how can I set a raw POST body data? I’ve tried

    `requestEntity.addPart(“”, new StringBody(“RAW DATA”));`

    I’ve created question with code snippet and problem description
    http://stackoverflow.com/questions/8965022/fill-in-post-body-with-multipartentity

    Reply
  34. joshmetran

    Hi Vikas,
    Im using your code and it’s working perfectly but the content type is not correct. why the content type is application/octec stream not image/*? Is there any possible solution on this?

    Thanks in advance

    Reply
  35. vincent

    hello, the executeMultiPartPost is working well thank you, u did a great job, but i’m kind of new with these stuff so can you post the server side here? i have no idea how to get the uploaded image and the path where it is stored thanks a lot

    Reply
  36. Tumza

    Guys please hel me out here im looking for a map activity in android , i checked the cronboys tutorial it doesnt work … does any one have a google map program in android please send it to me

    Reply
  37. Dipak Keshariya

    Hello Vikas,
    This code is working for me, but how to pass string value with image in your code, plz reply me asap.

    Thanks & Regards,
    Dipak Keshariya

    Reply
    1. Vikas Post author

      This will work:

      reqEntity.addPart(“photoCaption”, new StringBody(“sfsdfsdf”));

      First is field name and second is value to be posted

      Reply
  38. sudha

    Please can you tell me how to upload Video file over to the server please that would help me a lot. I am having an interview

    Reply
    1. caner

      you have to use blob type in server-side database.image upload is the same as posted here.just use sql commands(insert x ….)

      Reply
  39. pradip150Pradip

    Actually i take photo from Device camera then i should save in sd card. to save picture in sd card is too much big size. which i do resize image before save in sd card ?

    Reply
  40. ty

    Oh gee, finally i found one site that’s nice enough to post the whole codes. Thank you!! I really need this example for my school project :)

    cheers!

    Reply
  41. NitroZyKs

    Hi! i have a problem, i need to post an arrayList… anyone can tell me how can i cast the arrayList to a contentBody??… thanks.

    Reply
  42. Pingback: Android – Post Video with additional data to the server | Android Development tutorial | Android Development tutorial

  43. Vicky

    MultipartEntity multipartContent = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    after reaching above line my code do not work and don’t gives any error just hang the application plz help me.

    Reply
  44. Vicky

    MultipartEntity multipartContent = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    after reaching above line my code do not work and don’t gives any error just hang the application plz help me.

    Reply
  45. Pingback: Uploading sound file / photo won't work on android 2.3+ : Android Community - For Application Development

  46. Pingback: How to change ColdFusion function to a similar PHP function | Code and Programming

  47. Anil

    I don’t want to upload files to the Web Service but my question is how can I send whole .txt file and .doc file to the server on particular IP address. In my GUI I have to provide path of user choice. Means user has to choose the path of file that he/she wants to send…Please help me to solve my problem…Thank you…

    Reply
  48. Monzu

    Hi,
    Would you please give me the respective server side php code instead of coldfusion? I dont have coldfusion.

    Thanks

    Reply
  49. Ashraf

    Hi It help me lot and how to to do for all files(any file). You do with image with compression.

    Thanks

    Reply
  50. how to pick up random girls on facebook

    First off I would like to say fantastic blog! I had a quick question which I’d like to ask if you don’t mind.

    I was curious to know how you center yourself and clear your thoughts prior
    to writing. I have had trouble clearing my mind in getting my ideas out there.
    I truly do enjoy writing but it just seems like the first 10 to 15 minutes
    tend to be wasted just trying to figure out how to begin.
    Any ideas or hints? Many thanks!

    Reply
  51. comic shop

    Howdy are using WordPress for your blog platform?

    I’m new to the blog world but I’m trying to get started
    and create my own. Do you need any coding expertise to
    make your own blog? Any help would be really
    appreciated!

    Reply
  52. http://www.towerpaydayloans.co.uk/

    Do you mind if I quote a few of your articles as long as
    I provide credit and sources back to your weblog? My blog site is
    in the very same niche as yours and my visitors would genuinely benefit from
    some of the information you present here. Please let me know if this okay with you.
    Regards!

    Reply
  53. Dev

    Hey….I tried the source code and add httpmime-4.2.3.jar . But I am having the error
    import org.apache.http.entity.mime.HttpMultipartMode;
    import org.apache.http.entity.mime.MultipartEntity;
    import org.apache.http.entity.mime.content.ByteArrayBody;
    import org.apache.http.entity.mime.content.StringBody;
    Please help me out. Thank you.

    Reply
  54. Pingback: Android camera application - Android Solutions Solutions - Developers Q & A

  55. dev

    Hey Vikas….

    Will you please guide me how to do in server part with coldfusion. Please help me out.Thank you

    Reply
  56. accountant bendigo

    Hey there! I could have sworn I’ve been to this website before but after checking through some of the post I realized it’s new to me.
    Nonetheless, I’m definitely delighted I found it and I’ll be bookmarking and checking back often!

    Reply
  57. trampolines

    First of all I would like to say great blog!

    I had a quick question which I’d like to ask if you don’t mind.

    I was interested to know how you center yourself and clear
    your thoughts prior to writing. I have had trouble clearing my mind
    in getting my ideas out. I do enjoy writing however it just seems like the first 10 to 15 minutes are wasted simply
    just trying to figure out how to begin. Any suggestions or tips?
    Thank you!

    Reply
  58. top-or-flop.de

    I believe that suspended Teague for violating its scholarly person doings computer code, which interdicts buy twitter followers cheap cyberbullying, consorting to KSN-TV.
    And and so I have tells you that it’s a list of details and each
    of the particulars has a URL and a title, which
    is relevant to the activenesses. Why not try it as in that respect’s goin in
    there. Let buy twitter followers brassy me present
    you how 2, Michael Arrington out at TechCrunch. One in ten will die one, what is it named?

    Reply
  59. Dessie

    I blog frequently and I seriously thank you for your content.
    This great article has really peaked my interest.
    I’m going to bookmark your blog and keep checking
    for new information about once per week. I opted in for your Feed too.

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s