April 26, 2012

How to upload an image from Android device to server? – Method 4

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.

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="" 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" /></LinearLayout>


Now the java code.

package com.coderzheaven.pack;import;import;import;import;import;import;import;import;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;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);b = (Button)findViewById(;tv = (TextView)findViewById(;tv.setText("Uploading file path :- '/sdcard/android_1.png'");b.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {dialog =, "", "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);}}).start();}});}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 ServletFileInputStream fileInputStream = new FileInputStream(sourceFile);URL url = new URL(upLoadServerUri);conn = (HttpURLConnection) url.openConnection(); // Open a HTTPconnection tothe URLconn.setDoInput(true); // Allow Inputsconn.setDoOutput(true); // Allow Outputsconn.setUseCaches(false); // Don't use a Cached Copyconn.setRequestMethod("POST");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);dos.writeBytes(lineEnd);bytesAvailable = fileInputStream.available(); // create a buffer ofmaximum sizebufferSize = Math.min(bytesAvailable, maxBufferSize);buffer = new byte[bufferSize];// read file and write it into form...bytesRead =, 0, bufferSize);while (bytesRead > 0) {dos.write(buffer, 0, bufferSize);bytesAvailable = fileInputStream.available();bufferSize = Math.min(bytesAvailable, maxBufferSize);bytesRead =, 0, bufferSize);}// send multipart form data necesssary after file data...dos.writeBytes(lineEnd);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 //fileInputStream.close();dos.flush();dos.close();} catch (MalformedURLException ex) {dialog.dismiss();ex.printStackTrace();Toast.makeText(UploadImageDemo.this, "MalformedURLException", Toast.LENGTH_SHORT).show();Log.e("Upload file to server", "error: " + ex.getMessage(), ex);} catch (Exception e) {dialog.dismiss();e.printStackTrace();Toast.makeText(UploadImageDemo.this, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);}dialog.dismiss();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="" 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"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>

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.


<?php$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.


Leave a Reply Cancel reply

53 Comments to “How to upload an image from Android device to server? – Method 4”