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.