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

By | February 14, 2016

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

 

Now the java code.
UploadImageDemo.java

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;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        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() {			
			@Override
			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);					      
					    }
					  }).start();		 
				}
		});
    }
    
    public int uploadFile(String sourceFileUri) {
    	  String upLoadServerUri = "http://10.0.2.2/upload_test/upload_media_test.php";
    	  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.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 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(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="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">
            <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.

C:/xampp/htdocs/upload_test/upload_media_test.php.

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

 

56 thoughts on “How to upload an image from Android device to server? – Method 4

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

  2. david

    Hi,

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

    Please help me…

    Thanks

    Reply
    1. raji

      How to send string parameter along with image to server
      i can able to upload image using your code. but i dont know how to send my id and some description along with my image. how to recieve that id and description in php side. please help me. thanks in advance

      Reply
  3. david1

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

    Thanks

    Reply
    1. sarfaraz

      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

      Reply
  4. ama

    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)

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

  6. Kaminda

    Hi,

    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.

    Thanks

    Reply
  7. rachana

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

    Reply
    1. James Post author

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

      Reply
      1. dhara

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

        Reply
  8. Rasul

    Hi,

    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

    Reply
    1. James Post author

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

      Reply
    2. Rajal

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

      Reply
  9. golam Mostaeen

    thnx. it works nice.

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

    Reply
  10. Priyanka

    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…

    Reply
    1. James Post author

      That is some syntax error in the PHP server side.

      Reply
      1. Priyanka

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

        Reply
        1. suresh

          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

          Reply
      2. golam Mostaeen

        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 .

        Reply
    2. man yeap

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

      Reply
  11. sheelu

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

    Reply
  12. Priyanka

    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..
    Priyanka
    victory.payi77@gmail.com

    Reply
  13. golam Mostaeen

    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 .

    Reply
  14. suresh

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

    Reply
  15. sharodin

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

    Reply
    1. James Post author

      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.

      Reply
  16. Raju

    Hello,
    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.

    Reply
  17. Raman

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

    totalBytes is the size of file.

    long count = 0 ;
    while(true){
    int bytesRead = fStream.read(buffer,0,bufferSize);
    dos.write(buffer,0,bytesRead);
    count = count + bytesRead ;
    if(count == totalBytes){
    break;
    }
    }

    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 .

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

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

  20. recollections antique

    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.

    Cheers!

    Reply
  21. Andres

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

    Reply
  22. kaushik

    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 .

    Reply
  23. Nivedha

    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?

    Reply
    1. sd vipeen

      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.

      Reply
    1. James Post author

      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.

      Reply
  24. Shilpa

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

    Reply
    1. James Post author

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

      Reply
  25. Prerak

    Hello,
    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?

    Regards,
    Prerak

    Reply
    1. James Post author

      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.

      Reply
  26. ansh

    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.

    Reply
    1. James Post author

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

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