How to Upload Multiple files in one request along with other string parameters in android?

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.

73 thoughts on “How to Upload Multiple files in one request along with other string parameters in android?

  1. LamprosGk

    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:

    Reply
    1. James Post author

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

      Reply
    2. 181

      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?

      Reply
      1. nm

        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?

        Reply
        1. James Post author

          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.

          Reply
  2. 181

    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?

    Reply
  3. 181

    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

    Reply
    1. James Post author

      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.

      Reply
      1. 181

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

        Reply
        1. James Post author

          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

          Reply
    1. James Post author

      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.

      Reply
  4. 181

    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?

    Reply
  5. akubabas

    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

    Reply
  6. akubabas

    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 :(

    Reply
      1. sam

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

        Reply
  7. sam

    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.

    Reply
  8. hariprasad

    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)

    Reply
  9. slawomir

    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.

    Reply
    1. slawomir

      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.

      Reply
      1. James Post author

        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.

        Reply
        1. slawomir

          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

          Reply
          1. James Post author

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

        2. slawomir

          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

          Reply
          1. slawomir

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

  10. zeiss

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

    Reply
  11. shiwa

    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.

    Reply
  12. Zamani

    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 }

    Reply
    1. James Post author

      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.

      Reply
  13. Alvin tan

    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.

    Reply
  14. rachana

    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

    Reply
    1. James Post author

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

      Reply
      1. James Post author

        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?

        Reply
  15. Nev

    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

    Reply
  16. Anil

    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…

    Reply
    1. James Post author

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

      Reply
    1. James Post author

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

      Reply
  17. Tse

    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.

    Reply
  18. Reena

    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.

    Reply
  19. Vivek

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

    Reply

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>