Wednesday, 15 May 2013

How to upload file to server in android


If you are building an app that requires files to be uploaded on server you will need to follow this method. By using this method,  you will be able to upload a file from your SD Card.

We will be using httpmime-4.2.5.jar for this tutorial. You can download it from here. Extract the zip file and you will find jar file under lib folder.


  1. Create a new android project in Eclipse, and add the jar file to lib folder.
  2. Add android.permission.INTERNET and android.permission.WRITE_EXTERNAL_STORAGE in your manifest file.
  3. Use the following code :
 String address;
 MultipartEntity entity;
 File f;
 FileBody fb;
 entity = new MultipartEntity(
    HttpMultipartMode.BROWSER_COMPATIBLE);
 address = Environment.getExternalStorageDirectory()
    + "/temp.dat";
 f = new File(address);
 fb = new FileBody(f, "application/octect-stream");
 entity.addPart("file", fb);
 HttpClient httpclient = new DefaultHttpClient();
 HttpPost httppost = new HttpPost("Your URL Here");
 
 httppost.setEntity(entity);
 HttpResponse response = httpclient.execute(httppost);
 BufferedReader bufferedReader = new BufferedReader(
  new InputStreamReader(
   response.getEntity().getContent()));
 StringBuffer stringBuffer = new StringBuffer("");
 String line = "";
 String LineSeparator = System.getProperty("line.separator");
 while ((line = bufferedReader.readLine()) != null) {
  stringBuffer.append(line + LineSeparator);
 }
 bufferedReader.close();
 return stringBuffer.toString();
 } catch (ClientProtocolException e) {
  return e.toString();
 } catch (IOException e) {
  return e.toString();
 } 
Here we use MultipartEntity from the http library to add file for uploading.
f = new File(address);
fb = new FileBody(f, "application/octect-stream");
entity.addPart("file", fb);
We select the file given by address and then we get filebody using the FileBody Class and then add it to the entity.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("Your URL Here");
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
We create a new HttpClient and a HttpPost object, set entity and execute the reuqest.
Now android does not allow us to use network operations under the main thread, either we have to create a new thread or we use AsyncTask. You can Find the full source code here or download it here .
You can also use FTP library to uplaod the file which is better than this approach as described here.
Ads :
Buy Hard Drive, RAM, CD, DVD, USB on www.ebay.com
Electronics, Cars, Fashion, Collectibles, Coupons and More Online Shopping | eBay
www.ebay.co.uk | www.ebay.com.my