Hello all….

This post is also about uploading an image to server from your android device.
Previously I have shown three other methods to upload an image to a server.
Check these posts to refer this.

1. Uploading audio, video or image files from Android to server
2. How to Upload Multiple files in one request along with other string parameters in android?
3. ANDROID – Upload an image to a server.

These are for downloading files from the server.

1. How to Download an image in ANDROID programatically?
2. How to download a file to your android device from a remote server with a custom progressbar showing progress?

Now we will see another method.

Uploading files to Server

Before that I will show my sdcard contents. I have some images in my sdcard of which I am uploading one.
check this post to how to put files inside your emulator or device from eclipse.
How to add files like images inside your emulator in ANDROID?



First create a fresh project and name it “UploadImageDemo”.

Now this the layout file I am using for the main activity. (main.xml).
This contains a button which onclick will upload the file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" >
	<Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Upload File" android:id="@+id/but" />
	<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" android:id="@+id/tv" android:textColor="#00FF00" android:textStyle="bold" />


Now the java code.

package com.coderzheaven.pack;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class UploadImageDemo extends Activity {
	TextView tv;
	Button b;
	int serverResponseCode = 0;
	ProgressDialog dialog = null;
    public void onCreate(Bundle savedInstanceState) {
        b = (Button)findViewById(R.id.but);
        tv = (TextView)findViewById(R.id.tv);
        tv.setText("Uploading file path :- '/sdcard/android_1.png'");
        b.setOnClickListener(new OnClickListener() {			
			public void onClick(View v) {
				dialog = ProgressDialog.show(UploadImageDemo.this, "", "Uploading file...", true);
				 new Thread(new Runnable() {
					    public void run() {
					    	 runOnUiThread(new Runnable() {
				    			    public void run() {
				    			    	tv.setText("uploading started.....");
					   	 int response= uploadFile("/sdcard/android_1.png");
				         System.out.println("RES : " + response);					      
    public int uploadFile(String sourceFileUri) {
    	  String upLoadServerUri = "";
    	  String fileName = sourceFileUri;

    	  HttpURLConnection conn = null;
    	  DataOutputStream dos = null;  
    	  String lineEnd = "\r\n";
    	  String twoHyphens = "--";
    	  String boundary = "*****";
    	  int bytesRead, bytesAvailable, bufferSize;
    	  byte[] buffer;
    	  int maxBufferSize = 1 * 1024 * 1024; 
    	  File sourceFile = new File(sourceFileUri); 
    	  if (!sourceFile.isFile()) {
    	   Log.e("uploadFile", "Source File Does not exist");
    	   return 0;
	    	  try { // open a URL connection to the Servlet
	    	   FileInputStream fileInputStream = new FileInputStream(sourceFile);
	    	   URL url = new URL(upLoadServerUri);
	    	   conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
	    	   conn.setDoInput(true); // Allow Inputs
	    	   conn.setDoOutput(true); // Allow Outputs
	    	   conn.setUseCaches(false); // Don't use a Cached Copy
	    	   conn.setRequestProperty("Connection", "Keep-Alive");
	    	   conn.setRequestProperty("ENCTYPE", "multipart/form-data");
	    	   conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
	    	   conn.setRequestProperty("uploaded_file", fileName); 
	    	   dos = new DataOutputStream(conn.getOutputStream());
	    	   dos.writeBytes(twoHyphens + boundary + lineEnd); 
	    	   dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ fileName + "\"" + lineEnd);
	    	   bytesAvailable = fileInputStream.available(); // create a buffer of  maximum size
	    	   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(twoHyphens + boundary + twoHyphens + lineEnd);
	    	   // Responses from the server (code and message)
	    	   serverResponseCode = conn.getResponseCode();
	    	   String serverResponseMessage = conn.getResponseMessage();
	    	   Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
	    	   if(serverResponseCode == 200){
	    		   runOnUiThread(new Runnable() {
	    			    public void run() {
	    			    	tv.setText("File Upload Completed.");
	    			    	Toast.makeText(UploadImageDemo.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
	    	   //close the streams //
	      } catch (MalformedURLException ex) {  
	    	  Toast.makeText(UploadImageDemo.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
	    	  Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
    	  } catch (Exception e) {
    		  Toast.makeText(UploadImageDemo.this, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
    		  Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);  
    	  return serverResponseCode;  


This is the manifest file.
Make sure to add the internet permission in the AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.coderzheaven.pack" android:versionCode="1" android:versionName="1.0">
    <uses-permission android:name="android.permission.INTERNET"/>    
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".UploadImageDemo" android:label="@string/app_name">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />

OK Our Android part is over.

Now we will go to the server part.
I am using xampp in Windows. So my code goes to the htdocs folder inside my xampp folder.
ie. I am working on localhost, however you can replace the url with your own server name.
Inside the htdocs folder create a folder named “upload_test” and inside that create a file named “upload_media_test.php” and copy this code into it.

So the path is like this.



	$target_path1 = "uploads/";
	/* Add the original filename to our target path. Result is "uploads/filename.extension" */
	$target_path1 = $target_path1 . basename($_FILES['uploaded_file']['name']);
	if (move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path1)) {
		echo "The first file " . basename($_FILES['uploaded_file']['name']) . " has been uploaded.";
	} else {
		echo "There was an error uploading the file, please try again!";
		echo "filename: " . basename($_FILES['uploaded_file']['name']);
		echo "target_path: " . $target_path1;


I am uploading the file into a folder named “uploads” which is in the same directory as the above php code. So please create a “uploads” folder before running this code.

Also before running this code make sure that
1. Your server is running.
2. Your serverpath is correct.
3. The folder has correct write permissions.
4. You have the file to upload the file in the sdcard.

check this post to how to put files inside your emulator or device from eclipse.
How to add files like images inside your emulator in ANDROID?

OK now run the application and check the upload directory.
If the server response the ‘200’, your file has been uploaded.


Please leave your valuable comments on this post.




  1. Pingback: How to upload an image from Android device to server? – Method 4 « Emerson Barros

  2. david April 30, 2012 at 10:32 am


    I have only tomcat server so how can i run this application.

    Please help me…


  3. david1 April 30, 2012 at 10:35 am

    Nice tutorial It’s very useful for me.
    I have only tomcat server so how can i run this application.Please help me


    • sarfaraz September 8, 2015 at 12:15 pm

      bro its struck in uploading file not moving forward only help me server is on also gived permission in manifest and selected jpg file also as shown in the snapshot

  4. ama June 20, 2012 at 5:57 am

    I had to waste many time for complete upload task. Finally this example was excellent one. thank you. And can u send me a sample code for upload image file with string values.(String value etc)

  5. Pingback: How to Upload Multiple files in one request along with other string parameters in android?

  6. gauri August 10, 2012 at 7:24 am

    thanx it really help me alot great work.
    thanx again

  7. Kaminda October 19, 2012 at 3:58 am


    This is a great article. I could experience images uploaded to my site without wasting my time. There were few tags added to the code probably by an HTML editor but I could fix and get the application up and running in few minutes.


    • anynmous July 26, 2015 at 7:45 pm

      where did you change it?

  8. rachana November 2, 2012 at 11:01 am

    im using wamp server… when i hit the upload button it shows uploding bt its not uploded..
    in my logcat it shows source file doesnt exsist.
    y is tat??

    • James November 3, 2012 at 6:27 pm

      check the path of your selected file whether it exists or not.

      • dhara January 3, 2014 at 9:02 am

        i m getting the same error “source file does not exist”…….and the selected file path is right

        • dhara January 3, 2014 at 9:08 am

          plz help me ……

  9. rachana November 7, 2012 at 9:28 am


    THIS above link is perfectly working for me….
    but uploding multiple image is not working….

  10. Mandeep November 28, 2012 at 6:20 am

    Thanks a lot friend, i was searching for the same from last few days

  11. kiran February 4, 2013 at 9:07 am

    pls put asp.net code

  12. Rasul February 21, 2013 at 8:52 am


    when i run this code in android device it says that image is uploaded successfully, but when i see the folder in server it is not uploaded..
    Plz help

    • James February 21, 2013 at 3:23 pm

      check your folder permissions in the server side and check whether you have already created the folder for uploading the image.

    • Rajal November 20, 2014 at 5:49 am

      I have a same issue, I checked my server rights all perfect. You could solve this issue than could you please help?

  13. golam Mostaeen March 9, 2013 at 4:46 pm

    thnx. it works nice.

    But facing a little problem
    how can i rename the image during saving it to the uploads file
    thnx again…

  14. Priyanka March 9, 2013 at 4:48 pm

    that was really a good one..
    m working on wamp server..
    and on the server side an error is coming

    Notice: Undefined index: uploaded_file in C:\wamp\www\upload_test\upload_media_test.php on line 5

    Notice: Undefined index: uploaded_file in C:\wamp\www\upload_test\upload_media_test.php on line 6
    There was an error uploading the file, please try again!
    Notice: Undefined index: uploaded_file in C:\wamp\www\upload_test\upload_media_test.php on line 11
    filename: target_path: uploads/

    and also android when run is giving force close error..
    can you please help me…

    • Priyanka March 9, 2013 at 4:51 pm

      please post help to my mail

    • James March 9, 2013 at 5:17 pm

      That is some syntax error in the PHP server side.

      • Priyanka March 9, 2013 at 5:42 pm

        yeah can you help me with this..
        m struggling from a week..
        its my final year project

        • suresh March 14, 2013 at 5:12 am

          line 5:error is give u directory correctly like this “C:/which_dir_wnt_to_save”

          line6:upload image to emulator correctly give path name correct

          this two line error clear .line11 error automatic clear

      • golam Mostaeen March 10, 2013 at 8:00 am

        Can u give any post regarding GCM (google cloud message for android). My task is simple as the following:

        I have a web-server and let ” product ” is a table in that data base having attribute – product ID, product Name etc etc…
        When any user add any new entry from his mobile to that table all other users gets notification like : user X has added a new product . That’s all
        can u help to solve this problem. Expecting positive result 🙂 it’s urgent for me .

    • man yeap March 28, 2014 at 1:08 am

      Sir, I also facing the same problem can u post out the solution for this case?
      Thanks you very much.

  15. sheelu March 10, 2013 at 6:30 am

    m new to android and i tried this code..
    uploading image is coming.. but image is not uploaded..??
    I am getting the error as
    System err : the operation time timed out in the lod cat ???

    What is the reason for this??

    • James March 10, 2013 at 2:08 pm

      There is some problem in your internet connection.

  16. Priyanka March 10, 2013 at 7:26 am

    Hello sir..
    I am with my final year project on android..
    I am struggling to do things on my own..
    So if you are not minding please give your email..
    I have lot many doubts in developing my application..

    Please help me for this..

  17. golam Mostaeen March 10, 2013 at 8:01 am

    Can u give any post regarding GCM (google cloud message for android). My task is simple as the following:

    I have a web-server and let ” product ” is a table in that data base having attribute – product ID, product Name etc etc…
    When any user add any new entry from his mobile to that table all other users gets notification like : user X has added a new product . That’s all
    can u help to solve this problem. Expecting positive result 🙂 it’s urgent for me .

  18. suresh March 14, 2013 at 4:54 am

    this code working fine .

    PHP server side given coding just moving in localhost .i want to upload image to server using ftp or database . can u help …….

  19. sharodin March 26, 2013 at 9:26 am

    why the image after finish uploading. i open at folder xampp/htdoc/upload.. and i have that picture.. but cannot view that picture.. can u tell my why?

    how i want that picture after finish loading it automatically save on mysgl database..
    please answer my question… i hope so much… thanks

    • James March 29, 2013 at 3:44 pm

      Check your file extension if it is .png or jpg. Dont simply change the extension of a Image from .png to .jpg or viceversa. It will not open. You don’t need to save the image in the MYSQL database, simply save it’s path as a string in the database.

  20. Raju April 1, 2013 at 6:01 pm

    I want to upload multiple pics as I am trying to build an application to snap pics and send them to a server simultaneously in say a regular interval of 10 seconds. Any idea on how this can be achieved? Thanks in advance.

    • James April 2, 2013 at 5:42 pm

      Do the uploading in ASYNCTASK.

  21. Raman April 23, 2013 at 8:15 pm

    I am doing almost the same task except the writing binary data

    totalBytes is the size of file.

    long count = 0 ;
    int bytesRead = fStream.read(buffer,0,bufferSize);
    count = count + bytesRead ;
    if(count == totalBytes){

    Is the approach wrong ?
    Everytime I upload the file , the size is same and the name is also same but the file is corrupted. Please help .

  22. Pingback: what basename( $_FILES['uploadedfile']['name']) mean? - How-To Video

  23. Pingback: what basename( $_FILES['uploadedfile']['name']) mean? | BlogoSfera

  24. recollections antique August 25, 2013 at 7:15 am

    Do you mind if I quote a couple of your posts as long as I
    provide credit and sources back to your blog? My website is in the exact same
    area of interest as yours and my visitors would genuinely benefit from a lot of the information
    you present here. Please let me know if this okay with you.


    • James August 25, 2013 at 4:27 pm


  25. Andres November 3, 2013 at 10:16 am

    I cant find a way to use this method and send additional string parameters along the file. Any suggestions?

  26. kaushik November 28, 2013 at 5:42 am

    Hello sir when i run this code in my emulator i show message like file upload completed but i can’t see image in my httdoc->upload folder
    my local host server is complete running and i use xampp localhost server .

  27. Nivedha June 13, 2014 at 9:28 am

    Hi I have tried the given code but i’m getting the error “can’t create handler inside thread that has not called looper.prepare()”. What to do for this? Can anyone help?

    • sd vipeen August 21, 2014 at 1:39 pm

      i got the same error and a permission error along it. So i used the external storage permission in manifest file and everything was fine.

  28. ali November 28, 2014 at 8:18 am

    how to use asp.net vs php on the server side?

    • James November 30, 2014 at 8:49 am

      Sorry Ali, I am not aware of that, but let it be any programming language the data coming from server be always be in “String” format. You have to parse it in the Client side accordingly.

  29. Shilpa December 10, 2014 at 4:50 am

    WHat is that icon image? Did you already uploades any files in drawable xhdpi folder?

    • James December 14, 2014 at 1:38 pm

      You cannot get any images from the xhdpi folder, you need to select it from the gallery or sdcard.

  30. Prerak December 11, 2014 at 10:29 am

    This code worked perfectly fine for me. I got the file on the server side, but there is no extension to that file. When I try to open that file, it always asks me to choose a program to open with. If I choose the relevant application, file opens perfectly (eg. Adobe Reader for pdfs, Image Viewer for jpg, etc).
    Is there anyway to attach the extension to the uploaded file, so every time I don’t have to choose the relevant application?


    • James December 14, 2014 at 1:38 pm

      Prerak, you can check the extension in the server side code itself and create a new file with that extension and then write to it.

  31. ansh December 11, 2014 at 12:49 pm

    There is an error when i pressed upload file button after it the progress bar is appeared on the screen for a short time and thn the application stopped and the dialog box says that ” The application uploadImageDemo (process com.example.uploadimagedemo) has stopped unexpectedly. please try again.

    • James December 14, 2014 at 1:39 pm

      please check your log, what is the reason for crash and reply here.

  32. Pingback: Select an Image from gallery in ANDROID and show it in an ImageView. – CoderzHeaven

Leave a Reply

Your email address will not be published. Required fields are marked *




Theme by HermesThemes

Copyright © 2018 CoderzHeaven. All Rights Reserved

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.