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/

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

  1. 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?

      1. 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. 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

  3. 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?

  4. For java using rest webservice with jersey frame work.If possible please post some sample code..

  5. 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?

    1. 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.

  6. 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
    ????

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

      2. 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. 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.

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

  9. 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. ?

  10. 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 ?

    1. 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.

  11. 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 :)…

  12. 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 ?

      1. 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. 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.

  14. 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.

  15. 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.

  16. 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. ?

  17. 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.

  18. 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.

      1. 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. 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. 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

  20. 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! 🙂

  21. 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.

    1. 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??

  22. 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………

  23. 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

  24. 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

    1. 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.

  25. 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.

  26. 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

  27. 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

  28. 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;
    }

  29. 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?

  30. 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

  31. 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

  32. 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

  33. 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

  34. 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

  35. 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

    1. This will work:

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

      First is field name and second is value to be posted

  36. 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

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

  37. 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 ?

  38. 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!

  39. 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.

  40. 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.

  41. 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.

  42. 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…

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

    Thanks

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

    Thanks

  45. 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!

  46. 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!

  47. 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!

  48. 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.

  49. Hey Vikas….

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

  50. 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!

  51. 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!

  52. 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?

  53. 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.

  54. Hi just wanted to give you a quick heads up and let you know a few
    of the images aren’t loading properly. I’m not sure why
    but I think its a linking issue. I’ve tried it in two
    different internet browsers and both show the same results.

  55. Good day! I know this is somewhat off topic but I was wondering if you knew where I could locate a captcha plugin for my comment form?
    I’m using the same blog platform as yours and I’m having difficulty
    finding one? Thanks a lot!

  56. After compression when i chk the MIME Type of the Bitmpa it is :- “application/octet-stream”. How do i get imge/png or image/jpeg.

  57. for me this code is not working ……

    this is my wcf code
    [WebInvoke(Method = “POST”, UriTemplate = “/RequestImageFile”, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
    public Stream RequestImageFile(Stream fileStream)
    {
    Response response = new Response(); // Instantiate Response
    try
    {
    MultipartParser parser = new MultipartParser(fileStream);
    if (parser.Success)
    {
    string strFName = parser.Filename;
    string strContentType = parser.ContentType;
    byte[] byFileContent = parser.FileContents;
    System.Drawing.Image imgFileUpload = byteArrayToImage(byFileContent);

    string strTempPath = “~/” + GlobalDefaultValues.TemporaryUploadFilePath + “/” + CommUtil.GenerateUniqueNumber();
    string strUploadedFileExt = strFName.Substring(strFName.LastIndexOf(‘.’) + 1);
    string strId = CommUtil.GenerateUniqueNumber();
    string strFileName = strId + “_” + DateTime.Now.ToString(“dd-MM-yyyy”) + “_” + DateTime.Now.Hour + “_” + DateTime.Now.Minute + “_” + DateTime.Now.Second + “.” + strUploadedFileExt;
    string fileLoc = “~/” + GlobalDefaultValues.TemporaryUploadFilePath + “/” + EnumList.FileLocation.RequestItem + “/” + strId;
    new ImageModification().GetImageWaterMarked(HttpContext.Current.Server.MapPath(strTempPath + “/” + strFileName), HttpContext.Current.Server.MapPath(fileLoc + “/” + strFileName));
    File.Delete(HttpContext.Current.Server.MapPath(strTempPath + “/” + strFileName));
    Directory.Delete(HttpContext.Current.Server.MapPath(strTempPath));

    response.Status = true; // Operation Status Indicator
    response.Message = “Successful”; // Message
    response.Result = HttpContext.Current.Server.MapPath(fileLoc + “/” + strFileName); // Result

    }
    }
    catch (Exception Ex)
    {
    CommUtil.Elmah_SignalException(Ex, HttpContext.Current, “Service”);
    // Handle Exception
    response.Status = false; // Operation Status Indicator
    response.Message = Ex.Message; // Exception Message
    response.Result = null; // Result
    }

    // Instantiate Dictionary
    ClientResponse = new Dictionary();
    // Add Response
    ClientResponse.Add(“Response”, response);

    // Instantiate Serializer
    serializer = new JavaScriptSerializer();
    //Set Response Content Type
    WebOperationContext.Current.OutgoingResponse.ContentType = “application/json; charset=utf-8”;
    //Serialize Response
    return new MemoryStream(Encoding.UTF8.GetBytes(serializer.Serialize(ClientResponse)));
    }

    and this one is android code

    ////************ image upload to server*****************///////////
    Bitmap bitmap=BitmapFactory.decodeFile(imageFilePath);

    ByteArrayOutputStream out=new ByteArrayOutputStream();

    bitmap.compress(Bitmap.CompressFormat.PNG, 0, out);
    byte[] sendData =out.toByteArray();
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpPost postRequest =
    new HttpPost(“http://office.ajwebsolutions.in:81/API/EzyFindService.svc/RequestImageFile/”);
    ByteArrayBody bab = new ByteArrayBody(sendData,filename);
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    reqEntity.addPart(“image”, bab);
    postRequest.setEntity(reqEntity);

    HttpResponse response = httpClient.execute(postRequest,localContext);
    InputStream IN=response.getEntity().getContent();
    CommonJsonPost sj=new CommonJsonPost();
    String responseString=sj.InputstreamToString(IN);

    /****************end here**************/

    plse can you help me..

  58. Hi,
    I have small doubt that the following code
    reqEntity.addPart(“uploaded”, bab);
    reqEntity.addPart(“photoCaption”, new StringBody(“sfsdfsdf”));

    The above line of code what is”uploaded”is this key and what is the use of
    reqEntity.addPart(“photoCaption”, new StringBody(“sfsdfsdf”));

    and what is “photocaption” and “sfsdfsdf” which string is this

  59. Hey Dear, i am new in android. i have made an application that communicate between user by text messages using sockets and xampp server. now i want to attach some FILES like image and send it to other user… please help me…. thanks for any help…

  60. package ltd.pvt.itservicws.persist.schoolapp;

    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONArray;
    import org.json.JSONObject;

    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.ArrayList;

    /**
    * Created by Viyol on 9/26/2016.
    */
    public class Photogallery_frag extends Fragment
    {
    ArrayList al1 = new ArrayList();
    ListView ls1;

    public Photogallery_frag() {
    // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_photogallery_frag, container, false);
    ls1 = (ListView) rootView.findViewById(R.id.listview1);
    //new TheTask().execute(“http://10.0.2.2/school1/webservice1/viewphotogallery.php”);
    new TheTask().execute(“https://schoolapp21.000webhostapp.com/webservice1/viewPhotogallery.php”);
    return rootView;
    }
    class TheTask extends AsyncTask {
    String json = null;

    protected void onPostExecute(String json) {
    try {
    JSONArray jArray = new JSONArray(json);
    // Log.e(“post”,”post”);
    // Log.d(“Debug”, json.toString());
    // JSONObject jObj = new JSONObject(json);

    al1= new ArrayList () ;

    for (int i = 0; i < jArray.length(); i++) {
    JSONObject json_data = jArray.getJSONObject(i);

    String msg = "PhotogalleryId: " + json_data.getString("photogalleryid");
    msg =msg+ "\n Teacher Name :" + json_data.getString("name");
    msg = msg+ "\n Event Name :" + json_data.getString("eventname");
    msg =msg + "\n Image:" + json_data.getString("image");
    //msg = msg+"\n Time :" + json_data.getString("time");

    al1.add(msg);
    Log.e("msg",msg);
    }
    ArrayAdapter list = new ArrayAdapter(getContext(), R.layout.viewphotogallery, al1);
    ls1.setAdapter(list);

    } catch (Exception e1) {
    Log.e(“error”, e1.getMessage().toString());

    }
    }

    protected void onPreExecute() { // TODO Auto-generated method stub
    super.onPreExecute();
    }

    protected String doInBackground(String… params) {
    try {
    Log.e(“hello”, “hello1234”);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(params[0]);
    //httpPost.setEntity(new UrlEncodedFormEntity(param));

    HttpResponse httpResponse = httpClient.execute(httpPost);

    HttpEntity httpEntity = httpResponse.getEntity();
    InputStream is = httpEntity.getContent();

    BufferedReader reader = new BufferedReader(new InputStreamReader(is, “iso-8859-1″), 8);
    StringBuilder sb = new StringBuilder();

    // Toast.makeText(getBaseContext(), reader.read()+””, Toast.LENGTH_LONG).show();
    //String json;
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “\n”);

    }
    json = sb.toString();

    } catch (Exception e) {
    Log.e(“error”, “Network problem”);
    }
    return json;

    }

    }
    please help me,image not display

Leave a comment