Hello everyone,

I have shown two methods to upload files in android.
In today’s tutorial I will show another simple method to upload files. With this method you can upload multiple files in one request + you can send your own string parameters with them.

Here is another method on working with uploading of images.
How to upload an image from Android device to server? – Method 4

These are the things to do after creating the project.
1. You have to include two libraries in the your project build path(Download these libraries from here apache-mime4j-0.6.jar and httpmime-4.0.1.jar).
2. Add these libraries to the project build path.
3. Here you can see the the other things you need to remember while connecting to a server.

Refer the image

Note : I am working here on the local system as server. So I have used the server domain name as 10.0.2.2. Please change this according to your need.

OK Now open your main java file and copy this code into it.

package pack.coderzheaven;

import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
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 FileUploadTest extends Activity {

	private static final int SELECT_FILE1 = 1;
	private static final int SELECT_FILE2 = 2;
	String selectedPath1 = "NONE";
	String selectedPath2 = "NONE";
	TextView tv, res;
	ProgressDialog progressDialog;
	Button b1,b2,b3;
	HttpEntity resEntity;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        tv = (TextView)findViewById(R.id.tv);
        res = (TextView)findViewById(R.id.res);
        tv.setText(tv.getText() + selectedPath1 + "," + selectedPath2);
        b1 = (Button)findViewById(R.id.Button01);
        b2 = (Button)findViewById(R.id.Button02);
        b3 = (Button)findViewById(R.id.upload);
        b1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				openGallery(SELECT_FILE1);
			}
		});
        b2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				openGallery(SELECT_FILE2);
			}
		});
        b3.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(!(selectedPath1.trim().equalsIgnoreCase("NONE")) && !(selectedPath2.trim().equalsIgnoreCase("NONE"))){
					progressDialog = ProgressDialog.show(FileUploadTest.this, "", "Uploading files to server.....", false);
		       		 Thread thread=new Thread(new Runnable(){
		           	        public void run(){
		           	       		doFileUpload();
		           	            runOnUiThread(new Runnable(){
		           	                public void run() {
		           	                    if(progressDialog.isShowing())
		           	                    	progressDialog.dismiss();
		           	                }
		           	            });
		           	        }
		   	        });
		   	        thread.start();
				}else{
	  	                	Toast.makeText(getApplicationContext(),"Please select two files to upload.", Toast.LENGTH_SHORT).show();
				}
	        }
		});

    }

    public void openGallery(int req_code){

   	 	Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,"Select file to upload "), req_code);
   }

   public void onActivityResult(int requestCode, int resultCode, Intent data) {

	    if (resultCode == RESULT_OK) {
	    	Uri selectedImageUri = data.getData();
	        if (requestCode == SELECT_FILE1)
	        {
	            selectedPath1 = getPath(selectedImageUri);
	         	System.out.println("selectedPath1 : " + selectedPath1);
	        }
	        if (requestCode == SELECT_FILE2)
	        {
	            selectedPath2 = getPath(selectedImageUri);
	         	System.out.println("selectedPath2 : " + selectedPath2);
	        }
	        tv.setText("Selected File paths : " + selectedPath1 + "," + selectedPath2);
	    }
	}

    public String getPath(Uri uri) {
	    String[] projection = { MediaStore.Images.Media.DATA };
	    Cursor cursor = managedQuery(uri, projection, null, null, null);
	    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	    cursor.moveToFirst();
	    return cursor.getString(column_index);
	}

    private void doFileUpload(){

    	File file1 = new File(selectedPath1);
    	File file2 = new File(selectedPath2);
        String urlString = "http://10.0.2.2/upload_test/upload_media_test.php";
        try
        {
        	 HttpClient client = new DefaultHttpClient();
             HttpPost post = new HttpPost(urlString);
	         FileBody bin1 = new FileBody(file1);
	         FileBody bin2 = new FileBody(file2);
	         MultipartEntity reqEntity = new MultipartEntity();
	         reqEntity.addPart("uploadedfile1", bin1);
	         reqEntity.addPart("uploadedfile2", bin2);
	         reqEntity.addPart("user", new StringBody("User"));
	         post.setEntity(reqEntity);
	         HttpResponse response = client.execute(post);
	         resEntity = response.getEntity();
	         final String response_str = EntityUtils.toString(resEntity);
	         if (resEntity != null) {
	             Log.i("RESPONSE",response_str);
	        	 runOnUiThread(new Runnable(){
	 	                public void run() {
	 	                	 try {
	 	                		res.setTextColor(Color.GREEN);
	 							res.setText("n Response from server : n " + response_str);
	 							Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
	 						} catch (Exception e) {
	 							e.printStackTrace();
	 						}
	 	                   }
	 	            });
	         }
        }
        catch (Exception ex){
             Log.e("Debug", "error: " + ex.getMessage(), ex);
        }
      }
}

Now the layout for this file main.xml

<?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"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Multiple File Upload from CoderzHeaven"
    />
<Button
    android:id="@+id/Button01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Get First File">
</Button>
<Button
    android:id="@+id/Button02"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Get Second File">
</Button>
<Button
    android:id="@+id/upload"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Start Upload">
</Button>
<TextView
	android:id="@+id/tv"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Selected File path : "
    />

<TextView
	android:id="@+id/res"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text=""
   />
</LinearLayout>

Now the AndroidManifest file(Remember to add the permission for accessing internet)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="pack.coderzheaven"
      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=".FileUploadTest"
                  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>

Now the server side(Here it is written in PHP)
upload_media_test.php file contents

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

$target_path2 = $target_path2 . basename( $_FILES['uploadedfile2']['name']);
if(move_uploaded_file($_FILES['uploadedfile2']['tmp_name'], $target_path2)) {
    echo "n The second file ".  basename( $_FILES['uploadedfile2']['name']).
    " has been uploaded.";
} else{
    echo "There was an error uploading the file, please try again!";
    echo "filename: " .  basename( $_FILES['uploadedfile2']['name']);
    echo "target_path2: " .$target_path2;
}

$user = $_REQUEST['user'];
echo "n String Parameter send from client side : " . $user;
?>


Please leave your comments. If you like this post, please hit a “+1” for this post and share it across your networks.

 

84 Comments

  1. Deepak September 8, 2011 at 9:05 pm

    Hae, Thanx a lot for the wonderful work, it helped me a lot in my work when it was most required.

     
  2. Bhavna November 7, 2011 at 12:51 pm

    sir,
    i got an error Multipart entity doesnot Implement #get Content why???

     
    • James November 8, 2011 at 6:53 pm

      You didn’t include the jars in the build path as suggested.

       
  3. LamprosGk December 9, 2011 at 6:43 am

    Hi, do I have to change anything in the php code..?

    When I run the code, i get “upload complete..” toast on the screen but it hadnt uploaded any images an the server response is:

     
    • James December 14, 2011 at 7:40 am

      Hey LamprosGk check whether the changes you made might be affecting the code. This is a perfectly working code.

       
    • 181 December 27, 2011 at 7:40 am

      HI MATE,

      How u fixed your problem (Files not geting uploded in server,Even if t entire code goes fine)??

      Did u made ne changes or how it got uploaded for u?

       
      • nm June 12, 2012 at 2:13 pm

        Hi, I have a same problem get “upload complete..” toast on the screen but do not see my files on a server. How can I solve this?

         
        • James June 12, 2012 at 3:17 pm

          PLease check whether the selected file path and the variable names are corect. because if there is no problems such as crashing or somthing then these may be the errors.

           
    • Adan Vasconcelos September 6, 2014 at 1:59 am

      Check the permissions on your web server. The upload directory should be writable by PHP.

       
  4. 181 December 24, 2011 at 12:32 pm

    Hey tanks for your codes,,

    By the way what about the BASE64.java(n Uploading Image porj),,Those thing ned not 2 b used here?

     
    • James December 24, 2011 at 1:04 pm

      Base64.java is not needed here, instead of that we use two jars.

       
  5. 181 December 24, 2011 at 6:00 pm

    How to use these Libraries (apache-mime4j-0.6.jar and httpmime-4.0.1.)

    Cos the way i tried adding it doesn work for me

    (InSide my Project)->Android2.1->Build Path->Configure Build Path->Add External JARS–>httpmime-4.0.1….

    After reaching this point the folder(httpmime-4.0.1)leads to some (META-INF & org)and tat leads to anoter folder…

    cant able to choose 1 in tat…Jst let me know bout the way to fix tis…

    Tanks

     
    • James December 24, 2011 at 6:58 pm

      Don’t point to a folder, point to the jar file. First copy the two jars to a folder outside your project (eg:D:) then point to those jars. This should work because this is how we add jars to our project.

       
      • 181 December 24, 2011 at 9:02 pm

        Iam getting errors on tis line..

        42 setContentView(R.layout.main);(error in “main”)/////
        43
        44 tv = (TextView)findViewById(R.id.tv);(error in “tv”)////
        45 res = (TextView)findViewById(R.id.res);(error in “res”)//
        46 tv.setText(tv.getText() + selectedPath1 + “,” + selectedPath2);
        47 b1 = (Button)findViewById(R.id.Button01);(error in Button01)///////////////
        48 b2 = (Button)findViewById(R.id.Button02);error in “Button02”)//////////
        49 b3 = (Button)findViewById(R.id.upload);(error in “upload”)/////

        have jst copy pasted ur code,,checked the ID’s in XML which matchs wid the code,,bt stil geting the error??

         
        • James December 24, 2011 at 9:09 pm

          Please check the quotes(“), this may be causing the problem. Delete this quote and type this quote again. This happens when you copy something from a webpage.
          or try this
          edit the main.xml and type the code again

           
  6. 181 December 26, 2011 at 12:15 pm

    getting eror in tis Line James

    133 reqEntity.addPart(“uploadedfile1”, bin1);

     
    • James December 27, 2011 at 8:00 pm

      Please check the quotes(“), this may be causing the problem. Delete this quote and type this quote again. This happens when you copy something from a webpage.

       
  7. 181 December 27, 2011 at 7:37 am

    Hi James

    Finally Managed to fix all the bugs in t code,,Now everyting s clean,

    But t file s note getting Uploaded,,Wot maid b the problem?

     
    • James December 27, 2011 at 8:00 pm

      Did you tried uploading a smaller file to the server.

       
  8. Apisit March 1, 2012 at 12:52 pm

    Thx a lot

     
  9. akubabas March 13, 2012 at 7:12 am

    i got an error respone from server like this
    03-13 08:36:39.503: INFO/RESPONSE(294):
    03-13 08:36:39.503: INFO/RESPONSE(294): Warning: move_uploaded_file(uploads/1327629287763.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory in D:wwwuploadsuploader.php on line 5
    03-13 08:36:39.503: INFO/RESPONSE(294):
    03-13 08:36:39.503: INFO/RESPONSE(294): Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move ‘C:WINDOWSTempphp1FC.tmp’ to ‘uploads/1327629287763.jpg’ in D:wwwuploadsuploader.php on line 5
    03-13 08:36:39.503: INFO/RESPONSE(294): There was an error uploading the file, please try again!filename: 1327629287763.jpgtarget_path: uploads/1327629287763.jpg
    03-13 08:36:39.503: INFO/RESPONSE(294): String Parameter send from client side : User

    what the problem??thank you

     
    • James March 13, 2012 at 9:33 pm

      Check whether your directory exists or not.

       
  10. akubabas March 15, 2012 at 6:55 am

    yes i already have directory..but response from server like this..
    i try to change target_path with ‘/uploads’ its work but file can’t found in directory folder 🙁

     
    • James March 15, 2012 at 8:45 pm

      I think ‘/’ is the problem.

       
  11. sam March 21, 2012 at 12:52 pm

    I am not able to upload file on server. please help me

     
    • James March 21, 2012 at 10:43 pm

      Use some File upload software like “FileZilla” to upload the files to server.

       
      • sam March 28, 2012 at 11:41 am

        James a upload the folder on server but image is not able to upload.
        But this code is working correctly in xampp server.

         
      • sam March 28, 2012 at 12:33 pm

        I am upload the php on my server but they always run the else part of php and show error.

         
        • James March 28, 2012 at 11:19 pm

          Did you check the parameter name “uploadedfile1” is same in android and php side.

           
  12. sam March 21, 2012 at 4:19 pm

    how to run this code on server

     
  13. sam March 28, 2012 at 11:05 pm

    please anyone solve my problem
    I am upload the php on my server but they always run the else part of php and show error.

     
  14. hariprasad April 4, 2012 at 3:22 pm

    Hi when am run my php code on server side, that time i got error:
    There was an error uploading the file, please try again!filename: target_path: uploads/There was an error uploading the file, please try again!filename: target_path2: uploads/ String Parameter send from client side :

    Then run the android emulator means here am uploading 2 images from gallery then click the start upload button means itz displayed force close message…

    my logcat having error…the error is:
    04-03 19:49:49.178: E/dalvikvm(15116): Could not find class ‘org.apache.http.entity.mime.content.FileBody’, referenced from method pack.coderzheaven.FileUploadTest.doFileUpload
    04-03 19:55:34.878: E/AndroidRuntime(15116): FATAL EXCEPTION: Thread-9
    04-03 19:55:34.878: E/AndroidRuntime(15116): java.lang.NoClassDefFoundError: org.apache.http.entity.mime.content.FileBody
    04-03 19:55:34.878: E/AndroidRuntime(15116): at pack.coderzheaven.FileUploadTest.doFileUpload(FileUploadTest.java:128)
    04-03 19:55:34.878: E/AndroidRuntime(15116): at pack.coderzheaven.FileUploadTest.access$0(FileUploadTest.java:119)
    04-03 19:55:34.878: E/AndroidRuntime(15116): at pack.coderzheaven.FileUploadTest$3$1.run(FileUploadTest.java:68)
    04-03 19:55:34.878: E/AndroidRuntime(15116): at java.lang.Thread.run(Thread.java:1096)
    04-03 19:55:36.388: E/WindowManager(15116): Activity pack.coderzheaven.FileUploadTest has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@44ed1610 that was originally added here
    04-03 19:55:36.388: E/WindowManager(15116): android.view.WindowLeaked: Activity pack.coderzheaven.FileUploadTest has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@44ed1610 that was originally added here
    04-03 19:55:36.388: E/WindowManager(15116): at android.view.ViewRoot.(ViewRoot.java:247)
    04-03 19:55:36.388: E/WindowManager(15116): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
    04-03 19:55:36.388: E/WindowManager(15116): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
    04-03 19:55:36.388: E/WindowManager(15116): at android.view.Window$LocalWindowManager.addView(Window.java:424)
    04-03 19:55:36.388: E/WindowManager(15116): at android.app.Dialog.show(Dialog.java:241)
    04-03 19:55:36.388: E/WindowManager(15116): at android.app.ProgressDialog.show(ProgressDialog.java:107)
    04-03 19:55:36.388: E/WindowManager(15116): at android.app.ProgressDialog.show(ProgressDialog.java:90)
    04-03 19:55:36.388: E/WindowManager(15116): at pack.coderzheaven.FileUploadTest$3.onClick(FileUploadTest.java:65)
    04-03 19:55:36.388: E/WindowManager(15116): at android.view.View.performClick(View.java:2408)
    04-03 19:55:36.388: E/WindowManager(15116): at android.view.View$PerformClick.run(View.java:8816)
    04-03 19:55:36.388: E/WindowManager(15116): at android.os.Handler.handleCallback(Handler.java:587)
    04-03 19:55:36.388: E/WindowManager(15116): at android.os.Handler.dispatchMessage(Handler.java:92)
    04-03 19:55:36.388: E/WindowManager(15116): at android.os.Looper.loop(Looper.java:123)
    04-03 19:55:36.388: E/WindowManager(15116): at android.app.ActivityThread.main(ActivityThread.java:4627)
    04-03 19:55:36.388: E/WindowManager(15116): at java.lang.reflect.Method.invokeNative(Native Method)
    04-03 19:55:36.388: E/WindowManager(15116): at java.lang.reflect.Method.invoke(Method.java:521)
    04-03 19:55:36.388: E/WindowManager(15116): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
    04-03 19:55:36.388: E/WindowManager(15116): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
    04-03 19:55:36.388: E/WindowManager(15116): at dalvik.system.NativeStart.main(Native Method)

     
  15. slawomir May 1, 2012 at 2:36 pm

    Hi guys,
    I am getting very strange error: Dalvikvm exception instantiating org.apache.http.entity.mime.content.FileBody. It can not find FileBody.class. I ve been trying to find any solution on the web, but no results so far. If somebody know how to sort it out, any help much appricieted.

     
    • slawomir May 1, 2012 at 3:00 pm

      04-30 15:25:51.646: E/dalvikvm(12664): Could not find class ‘org.apache.http.entity.mime.content.FileBody’, referenced from method pack.coderzheaven.FileUploadTest.doFileUpload

      That is exacly what i am getting.

       
      • James May 1, 2012 at 6:17 pm

        Did you add the jar to the referenced libraries in the buildpath. I think you didn’t do it, that is why the system can’t find the class.

        Read the post carefully…
        Follow these steps exactly..

        These are the things to do after creating the project.
        1. You have to include two libraries in the your project build path(Download these libraries from here apache-mime4j-0.6.jar and httpmime-4.0.1.jar).
        2. Add these libraries to the project build path.
        3. Here you can see the the other things you need to remember while connecting to a server.

         
        • slawomir May 3, 2012 at 12:30 pm

          I followed exacly that link so adding libs is not an issue:

          http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29

          if it was just the case of wrongly added libs it wouldnt even compile, this fellow had the same error and fix for that is described below:

          http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29

          I wonder what you think about it James. Your tuts are awesome and I would appriciate help form you.

          All the best,
          I can post picture of my project to you if you want to see tree of that project

          Kind Regards

           
          • James May 3, 2012 at 12:55 pm

            Hello slawomir :- Those links are good. Now what is that you want from me? Are you getting any errors following my post. Please explain.

             
        • slawomir May 3, 2012 at 1:42 pm

          I am getting the class can be found

          04-30 15:25:51.646: E/dalvikvm(12664): Could not find class ‘org.apache.http.entity.mime.content.FileBody’

          Can you say if Dennises https://groups.google.com/forum/#!msg/android-developers/QQSWZ_sWdgU/ib3IOHhhZ9YJ
          way of overcoming that problem is the way to go.
          Sorry I added wrong second link last time. Every lib is added still cant find FileBody Class. I have no idea what is worng. Dennis wrote that problem started with using sdk17???
          Please help

           
          • slawomir May 3, 2012 at 6:50 pm

            Sorted works like a dream.
            Dennis was right you have to use src code instead libs 🙂

             
          • slawomir May 3, 2012 at 6:58 pm

            And thank you again for tuts James

             
  16. zeiss May 17, 2012 at 9:49 am

    hello,thank you for your code.I have one question ,I just upload one file(the second)when i select two,why? thank you

     
  17. shiwa June 20, 2012 at 6:10 pm

    Thank you very much,
    And other, if you have any trouble with file not found, please use these jar file version
    httpcomponents-client-4.1.2-bin
    thank you again.

     
    • James June 20, 2012 at 6:30 pm

      Check out the link again.

       
  18. Zamani June 22, 2012 at 12:49 pm

    I’m getting force close error.. i’m using emulator..[The Application camera]

    : Starting: Intent { act=android.intent.action.PICK dat=content://media/external/images/media cmp=com.android.gallery/com.android.camera.ImageGallery }

     
  19. khushbu June 26, 2012 at 7:25 am

    thanks !!!
    it help me a lot..
    gr8 works keep it up 🙂

     
  20. kuek9118 July 2, 2012 at 9:22 am

    hi…i using your example ..it help me alot, however i get some problem when i need check image type in php…can you help me?
    contact me by email, kuek9118@gmail.com thanks

     
    • James July 2, 2012 at 5:30 pm

      What is the error that you are getting?
      Can you send me the error?

      Actually there is no need to check the image type in php. whatever
      file you are sending, whether ‘jpg’ or ‘png’ the same type file will
      be created in the server.

       
  21. Alvin tan August 11, 2012 at 9:42 pm

    DalvikVM[localhost:8600]
    Thread [ main] (Running)
    Thread [ Binder Thread #16] (Running)
    Thread [ Binder Thread #15] (Running)
    Thread [ Binder Thread #14] (Running)
    Thread [ Binder Thread #13] (Running)
    Thread [ Binder Thread #12] (Running)
    Thread [ Binder Thread #11] (Running)
    Thread [ Binder Thread #10] (Running)
    Thread [ Binder Thread #9] (Running)
    Thread [ Binder Thread #8] (Running)
    Thread [ Binder Thread #7] (Running)
    Thread [ Binder Thread #6] (Running)
    Thread [ Binder Thread #5] (Running)
    Thread [ Binder Thread #4] (Running)
    Thread [ Binder Thread #3] (Running)
    Thread [ Binder Thread #2] (Running)
    Thread [ Binder Thread #1] (Running)
    Thread [ Thread-24] (Suspended (exception NoClassDefFoundError))
    FileUploadTest.doFileUpload() line: 130
    FileUploadTest.access$0(FileUploadTest) line: 121
    FileUploadTest$3$1.run() line: 69
    Thread.run() line: 1019
    Got this error when i tried to upload it.

     
  22. rachana November 7, 2012 at 9:25 am

    im getting the below error.. y is it??
    and emulator is showing force close.. help me:(

    java.lang.NoClassDefFoundError: org.apache.http.entity.mime.content.FileBody

     
    • James November 7, 2012 at 6:01 pm

      Add the jars as instructed in the post. Also check the ‘Order and Export” tab in the project properties.

       
      • rachana November 8, 2012 at 10:02 am

        i hav added jar files in referenced libraries…
        still getting force close error…
        logcat shows

        Could not find class ‘org.apache.http.entity.mime.content.FileBody’,

        referenced from method com.example.upload.FileUploadTest.doFileUpload…

        i hav checked order and export.. my jar files are in tat.

        http://www.coderzheaven.com/2012/04/26/upload-image-android-device-server-method-4/ THIS LINK IS PERFECTLY WORKING FOR ME….

         
        • rachana November 8, 2012 at 10:05 am

          y im getting those error, i hav added jar files.. when i hit start upload button it shows force close..

           
  23. rachana November 15, 2012 at 11:05 am

    thanku so much… this worked fine for me!!!!!!!!!!

     
  24. rachana November 23, 2012 at 7:34 am

    the above code works fine for me…. bt i want to upload images to mysql database using blob??? plz help…

     
    • Nev December 6, 2012 at 1:23 pm

      i have solotion for this. dont store blob in mysql but store the path of the file in database.. and call it.

       
      • James December 7, 2012 at 2:13 am

        This is an example of how to store an image in SQL Database. Also if you store the path and later when the file gets deleted, then what will you do?

         
        • Nev December 7, 2012 at 5:07 pm

          use delete query to delete in database the row of the file and use unlink(“$file”); to delete files in folder.

           
  25. Nev December 6, 2012 at 12:57 pm

    hi wats the maximum capacity of this code to transfer files? im sending a mp3 format file that has 3mb but doesn’t work. its only for small files?.Plz help

     
  26. Anil January 16, 2013 at 10:47 am

    I am developing an application in which I have to send file such as .txt, .doc, Images to the server. In my application, android device is client and WiFi printer is generating output. Whatever you type in application that will be the output from the printer. In this, I have to give IP address and port number on which that Printer operates. I have seen your code but I am confused that where should I give IP address and port number?? Help me to solve this. Thank you…

     
  27. duong February 20, 2013 at 8:47 am

    I want to do on asp.net server side. Can you help me?

     
  28. Roshni March 15, 2013 at 9:40 am

    Hi,
    i m getting error in php file. Can u tel me the folder where my files are been uploaded

     
    • James March 15, 2013 at 3:24 pm

      Please check the upload directory coded in the php file. Make sure you have the write permission in the server to upload image.

       
  29. koko August 12, 2013 at 10:33 am

    Hi
    how can i post image + string to server with your code?
    thanks

     
    • James August 15, 2013 at 1:28 pm

      This example actually demonstrates this.

       
  30. Leo September 10, 2013 at 12:08 pm

    Thank you very much…..sir……This code 100% working without Error……

     
  31. nickdecillo December 9, 2013 at 7:00 am

    hi i already finish code it to eclipse but my problem is when I’m able to click the the upload button, it doesnt continue to upload.. why its that happen?

     
    • James December 15, 2013 at 3:41 pm

      can’t say much with this information, but make sure that you add the internet permission in the AndroidManifest file.

       
  32. Tse February 27, 2014 at 5:02 am

    Hi James,

    I can only select one image, not two. When i click button2 and select second image first image selectedpath1 goes to null and selectedpath2 is showing correct path to the second image. My targeted API is 16. Looks like it happens when you have 3 different gallery apps to select the image.

     
    • Tse February 27, 2014 at 5:04 am

      I mean null is actually “NONE”

       
  33. Reena April 1, 2014 at 6:15 am

    Hi,
    I unable to upload the image using above code, its not working for me, i am getting message that image uploaded successfully but when i checked to the server there is no any entry.

     
    • James April 3, 2014 at 5:23 pm

      Check the server folder permission and your upload URL.

       
  34. Vivek August 18, 2014 at 6:13 am

    am geting error on following line..
    import org.apache.http.client.methods.HttpPost;
    error is: syntax error on tokens,SimpleName Expected instead…

     
  35. Sunnatilla August 21, 2014 at 9:08 pm

    Thanks a lot for wonderful tutorial, it help to store my time, thanks a lot

     
  36. Maga September 11, 2014 at 10:10 pm

    Thank you very much for this tutorial it helped me a lot. 🙂

     
  37. Sandeep November 5, 2014 at 8:17 am

    Hello sir its great, working for me but when I select the pdf or other format file to upload its shouts
    unfortunately stop this application.
    can u please help me to upload pdf and doc file from sdcard and from drive.

     
    • James November 5, 2014 at 8:29 am

      please check in the Logcat the reason for error and paste it in the comment, then only we can fix it.
      Make sure you have INTERNET permission in the manifest.

       
  38. nimmi November 12, 2014 at 1:15 pm

    Hi,
    I am trying to upload other type of files using
    intent.setType(“file/*”); and I am getting NullPointerException in getPath().
    I think it is because of the line
    String[] projection = { MediaStore.Images.Media.DATA };
    So what should I give instead of MediaStore.Images. Can u please help me

     
  39. Kingzp July 21, 2015 at 9:14 am

    A very helpful tutorial, in my case I want to upload files a automatically to the server, after they are been captured. I should check if wifi is on, before sending them. So if wifi is on I send. How would I send them automatically to sever? Please help, M a newbie to android. I was using on-click button it was working fine, now I have to send them to server automatically.

     
  40. Ravi Shrivastava March 18, 2017 at 12:05 pm

    what if file size is more than 2 mb , 5mb . I am not able to send to send big file size in 3g network.

     
  41. Nikit June 19, 2017 at 11:23 am

    can we upload multiple videos to server by this code..

     
    • James June 20, 2017 at 5:36 am

      Yes

       
  42. Srilatha October 24, 2017 at 7:35 am

    Hi,
    I’m not getting any path. If i give path manually its closing the app before going into doFileUpload method. Please help me. Any answers should be appreciated.

     
    • James October 24, 2017 at 12:44 pm

      You mean you are not getting the selected file path from the gallery?. Try using any File Explorer and get the path and hardcode the path to test. Also make sure that you have necessary permissions.

       

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.