Category Archives: Uploaing a File

How to find your Google Plus ID

This is so simple

1. Go to your Google + account (https://plus.google.com/).

2. Click on the Profile icon on the Left.

3. If you look at the URL in the address bar, it should look something like this:

https://plus.google.com/104653270154306099169/posts

4. The long numerical string in the URL is your Google+ ID. Here is CoderzHeaven’s from the URL above:

104653270154306099169/

Google + CoderzHeaven

Uploading and Downloading of files – Popular and Useful posts from CoderzHeaven

Here are the links of my most popular posts on downloading and uploading of files to and from your android device.

uploading and downloading images in android

1. How to download a file from a remote site in android? – Another simple example – Method -3

2. How to download a file to your android device from a remote server with a custom progressbar showing progress?

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

4. Uploading audio, video or image files from Android to server

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

6. How to Download an image in ANDROID programatically?

7. ANDROID – Upload an image to a server

Please leave your comments if you find these posts useful.

Join the Forum discussion on this post

How to download a file from a remote site in android? – Another simple example – Method -3

Hello all …….

I have shown many examples on how to download and upload files in android through this site.

These are other methods for downloadign a file in android.

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?

I have shown four 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.
4. How to upload an image from Android device to server? – Method 4

This is yet another example on how to do download a file.

So this is the java code that downloads the file.

package com.coderzheaven.pack;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class DownloadFileDemo extends Activity {
	
	String dwnload_file_path = "http://coderzheaven.com/sample_folder/sample_file.png";
	String dest_file_path = "/sdcard/dwnloaded_file.png";
	Button b1;
	ProgressDialog dialog = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        b1 = (Button)findViewById(R.id.Button01);
        b1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
				dialog = ProgressDialog.show(DownloadFileDemo.this, "", "Downloading file...", true);
				 new Thread(new Runnable() {
			            public void run() {
			            	 downloadFile(dwnload_file_path, dest_file_path);
			            }
			          }).start();				
			}
		});
    }
    
    public void downloadFile(String url, String dest_file_path) {
    	  try {
    		  File dest_file = new File(dest_file_path);
    	      URL u = new URL(url);
    	      URLConnection conn = u.openConnection();
    	      int contentLength = conn.getContentLength();

    	      DataInputStream stream = new DataInputStream(u.openStream());

	          byte[] buffer = new byte[contentLength];
	          stream.readFully(buffer);
	          stream.close();

	          DataOutputStream fos = new DataOutputStream(new FileOutputStream(dest_file));
	          fos.write(buffer);
	          fos.flush();
	          fos.close();
	          hideProgressIndicator();
	          
    	  } catch(FileNotFoundException e) {
    		  hideProgressIndicator();
    	      return; 
    	  } catch (IOException e) {
    		  hideProgressIndicator();
    	      return; 
    	  }
    }
    
    void hideProgressIndicator(){
    	runOnUiThread(new Runnable() {
		    public void run() {
		    	dialog.dismiss();
		    }
		});  
    }
}

This is the xml file that contains the button.

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="File Download Demo from Coderzheaven \n\nFile to download : http://coderzheaven.com/sample_folder/sample_file.png \n\nSaved Path : sdcard/\n"
    />
<Button 
	android:text="Download File" 
	android:id="@+id/Button01" 
	android:layout_width="wrap_content" 
	android:layout_height="wrap_content">
</Button>
</LinearLayout>

Note : Please add these two permissions in the AndroidManifest.xml

  <uses-permission android:name="android.permission.INTERNET"/>    
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

download file android

download file android

Please leave your comments and also share this post if you like it.

How to download a file to your android device from a remote server with a custom progressbar showing progress?

Actually this is really simple.

I have already posted an example for how to download a file in this post.

How to Download an image in ANDROID programatically?

This is another one little different with a progressbar included.

Previously I have shown three other methods to upload files 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.

OK We will start now.
This is the file we are going to download.

http://coderzheaven.com/sample_folder/sample_file.png

First we will create a simple layout with a button that will download a file on it’s onClick event.

This is the contents of 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:id="@+id/tv1"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Downloading File with ProgressBar Demo From Coderzheaven"
    />
<Button 
	android:id="@+id/b1"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Download File"
    android:onClick="downloadFile"
    />
</LinearLayout>

download a file to your android device from a remote server with a custom progressbar showing progress

Now we will write the java code to download the file.
Copy this code to your main java file. My file is named “DownloadFileDemo1.java”.

package com.coderzheaven.pack;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class DownloadFileDemo1 extends Activity {
	
    ProgressBar pb;
    Dialog dialog;
    int downloadedSize = 0;
    int totalSize = 0;
    TextView cur_val;
    String dwnload_file_path = "http://coderzheaven.com/sample_folder/sample_file.png";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      
        Button b = (Button) findViewById(R.id.b1);
        b.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				 showProgress(dwnload_file_path);
			        
			        new Thread(new Runnable() {
			            public void run() {
			            	 downloadFile();
			            }
			          }).start();
			}
		});
    }
  	    
    void downloadFile(){
    	
    	try {
    		URL url = new URL(dwnload_file_path);
    		HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

    		urlConnection.setRequestMethod("GET");
    		urlConnection.setDoOutput(true);

    		//connect
    		urlConnection.connect();

    		//set the path where we want to save the file    		
    		File SDCardRoot = Environment.getExternalStorageDirectory(); 
    		//create a new file, to save the downloaded file 
    		File file = new File(SDCardRoot,"downloaded_file.png");
 
    		FileOutputStream fileOutput = new FileOutputStream(file);

    		//Stream used for reading the data from the internet
    		InputStream inputStream = urlConnection.getInputStream();

    		//this is the total size of the file which we are downloading
    		totalSize = urlConnection.getContentLength();

    		runOnUiThread(new Runnable() {
			    public void run() {
			    	pb.setMax(totalSize);
			    }			    
			});
    		
    		//create a buffer...
    		byte[] buffer = new byte[1024];
    		int bufferLength = 0;

    		while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
    			fileOutput.write(buffer, 0, bufferLength);
    			downloadedSize += bufferLength;
    			// update the progressbar //
    			runOnUiThread(new Runnable() {
    			    public void run() {
    			    	pb.setProgress(downloadedSize);
    			    	float per = ((float)downloadedSize/totalSize) * 100;
    			    	cur_val.setText("Downloaded " + downloadedSize + "KB / " + totalSize + "KB (" + (int)per + "%)" );
    			    }
    			});
    		}
    		//close the output stream when complete //
    		fileOutput.close();
    		runOnUiThread(new Runnable() {
			    public void run() {
			    	// pb.dismiss(); // if you want close it..
			    }
			});    		
    	
    	} catch (final MalformedURLException e) {
    		showError("Error : MalformedURLException " + e);  		
    		e.printStackTrace();
    	} catch (final IOException e) {
    		showError("Error : IOException " + e);  		
    		e.printStackTrace();
    	}
    	catch (final Exception e) {
    		showError("Error : Please check your internet connection " + e);
    	}    	
    }
    
    void showError(final String err){
    	runOnUiThread(new Runnable() {
		    public void run() {
		    	Toast.makeText(DownloadFileDemo1.this, err, Toast.LENGTH_LONG).show();
		    }
		});
    }
    
    void showProgress(String file_path){
    	dialog = new Dialog(DownloadFileDemo1.this);
    	dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    	dialog.setContentView(R.layout.myprogressdialog);
    	dialog.setTitle("Download Progress");

    	TextView text = (TextView) dialog.findViewById(R.id.tv1);
    	text.setText("Downloading file from ... " + file_path);
    	cur_val = (TextView) dialog.findViewById(R.id.cur_pg_tv);
    	cur_val.setText("Starting download...");
    	dialog.show();
    	
    	pb = (ProgressBar)dialog.findViewById(R.id.progress_bar);
    	pb.setProgress(0);
    	pb.setProgressDrawable(getResources().getDrawable(R.drawable.green_progress));  
    }
}

OK now we have to make a layout for the progressdialog since it is a custom one.

create a new xml file inside res/layout folder and name it myprogressdialog.xml and copy this code into it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/layout_root"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="10dp"
              >
    
    <TextView 
    	android:id="@+id/tv1"
      	android:layout_width="wrap_content"
      	android:layout_height="wrap_content"
      	android:textColor="#FFF"
      	android:text="hello"
      	android:textStyle="bold"  
    />
       
    <TextView 
    	android:id="@+id/cur_pg_tv"
      	android:layout_width="wrap_content"
      	android:layout_height="wrap_content"
      	android:textColor="#0F0"
      	android:text="hello"
      	android:layout_marginTop="5dp"
      	android:textStyle="bold|italic"    />       
    <ProgressBar   
		android:id="@+id/progress_bar"  
		android:layout_width="fill_parent"  
		android:layout_height="wrap_content"  
		android:progress="0"  
		android:layout_marginTop="5dp"
		android:layout_marginBottom="10dp"
		style="?android:attr/progressBarStyleHorizontal"  
		android:maxHeight="10dip"  
		android:minHeight="10dip"  
	/>  
	
</LinearLayout>

Now create a new file inside res/drawable folder and name it “green_progress.xml” and copy this code into it.
This xml is used for giving a green color to the progressbar.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@android:id/background">
    <shape>
        <corners android:radius="5dip" />
        <gradient
                android:startColor="#ff9d9e9d"
                android:centerColor="#ff5a5d5a"
                android:centerY="0.75"
                android:endColor="#ff747674"
                android:angle="270"
        />
    </shape>
</item>
<item
    android:id="@android:id/progress">
    <clip>
        <shape>
            <corners
                android:radius="5dip" />
            <gradient
                	android:startColor="@color/greenStart"
                    android:centerColor="@color/greenMid"
                    android:centerY="0.75"
                    android:endColor="@color/greenEnd"
                    android:angle="270"
            />
        </shape>
    </clip>
</item>
</layer-list>

OK now we have customized the progressbar.

This line sets the progressbar to green color.

pb.setProgressDrawable(getResources().getDrawable(R.drawable.green_progress));

The showProgress() method inside the java code will invoke the custom progressbar.

Now the main thing..
Dont forget to add the permissions to the manifest file.

These two are the permissions we need .


This is the AndroidManifest file for this example.

<?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" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".DownloadFileDemo1"
                  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> 

download a file to your android device from a remote server with a custom progressbar showing progress

download a file to your android device from a remote server with a custom progressbar showing progress

download a file to your android device from a remote server with a custom progressbar showing progress

The file will be downloaded to the sdcard root. Please go to the DDMS perpective and open the File Explorer and expand the SDCARD to see the downloaded file.

Check the screen shot..

download a file to your android device from a remote server with a custom progressbar showing progress

Download.

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="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.

Uploading audio, video or image files from Android to server

Hello everyone,

Check out the popular posts from Coderzheaven.com

Uploading and Downloading of files – Popular and Useful posts from CoderzHeaven

In one of the previous posts I have shown one method to upload an image in android.
Here is another method to upload a media file like images,audio or video in android.
Here is the main java file that does the upload.
Here I am trying to open audio from the gallery. However you can change it to image or video according to your need.
The code for upload will not change since we change only the code for opening the gallery. We use only the path of the selected file whether it is image or video or audio to upload.

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?

package pack.coderzheaven;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

public class UploadAudioDemo extends Activity {

	private static final int SELECT_AUDIO = 2;
	String selectedPath = "";

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

        openGalleryAudio();
    }

    public void openGalleryAudio(){

   	Intent intent = new Intent();
        intent.setType("audio/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,"Select Audio "), SELECT_AUDIO);
   }

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

	    if (resultCode == RESULT_OK) {

	        if (requestCode == SELECT_AUDIO)
	        {
	        	System.out.println("SELECT_AUDIO");
	            Uri selectedImageUri = data.getData();
	            selectedPath = getPath(selectedImageUri);
	         	System.out.println("SELECT_AUDIO Path : " + selectedPath);
	         	doFileUpload();
	        }

	    }
	}

    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(){
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        String lineEnd = "rn";
        String twoHyphens = "--";
        String boundary =  "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1*1024*1024;
        String responseFromServer = "";
        String urlString = "http://your_website.com/upload_audio_test/upload_audio.php";
        try
        {
         //------------------ CLIENT REQUEST
        FileInputStream fileInputStream = new FileInputStream(new File(selectedPath) );
         // open a URL connection to the Servlet
         URL url = new URL(urlString);
         // Open a HTTP connection to the URL
         conn = (HttpURLConnection) url.openConnection();
         // Allow Inputs
         conn.setDoInput(true);
         // Allow Outputs
         conn.setDoOutput(true);
         // Don't use a cached copy.
         conn.setUseCaches(false);
         // Use a post method.
         conn.setRequestMethod("POST");
         conn.setRequestProperty("Connection", "Keep-Alive");
         conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
         dos = new DataOutputStream( conn.getOutputStream() );
         dos.writeBytes(twoHyphens + boundary + lineEnd);
         dos.writeBytes("Content-Disposition: form-data; name="uploadedfile";filename="" + selectedPath + """ + lineEnd);
         dos.writeBytes(lineEnd);
         // create a buffer of maximum size
         bytesAvailable = fileInputStream.available();
         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);
         // close streams
         Log.e("Debug","File is written");
         fileInputStream.close();
         dos.flush();
         dos.close();
        }
        catch (MalformedURLException ex)
        {
             Log.e("Debug", "error: " + ex.getMessage(), ex);
        }
        catch (IOException ioe)
        {
             Log.e("Debug", "error: " + ioe.getMessage(), ioe);
        }
        //------------------ read the SERVER RESPONSE
        try {
              inStream = new DataInputStream ( conn.getInputStream() );
              String str;

              while (( str = inStream.readLine()) != null)
              {
                   Log.e("Debug","Server Response "+str);
              }
              inStream.close();

        }
        catch (IOException ioex){
             Log.e("Debug", "error: " + ioex.getMessage(), ioex);
        }
      }
}

Now the server side , the code is written in Php.

<?php
// Where the file is going to be placed
$target_path = "uploads/";

/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

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

Things to keep in mind
1. Make sure your server is running.
2. Your server file path should be right.
3. Check your folder write permission in the server.

Please leave your valuable comments.
Enjoy.

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.

ANDROID – Upload an image to a server

Hi ANDROIDians in today’s tutorial I will show you how to send an image to server using POST method in ANDROID.
Uploading an image to server is a basic requirement in many of our application.
Sending data to server which is using a PHP Script is already explained in this example .
Now in this example I will show you how to send an image file.
For that first we have to read the file, put it in nameValuePairs and then send using HttpPost.

I have already shown you three other methods on uploading a file to server. If you want you can check these posts.
1. How to Upload Multiple files in one request along with other string parameters in android?
2. Uploading audio, video or image files from Android to server.
3. How to upload an image from Android device to server? – Method 4

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 can we quickly go to the code.

This is the main java file source code UploadImage.java

package pack.coderzheaven;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.Toast;

public class UploadImage extends Activity {
	InputStream inputStream;
	    @Override
	public void onCreate(Bundle icicle) {
	        super.onCreate(icicle);
	        setContentView(R.layout.main);

	        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon);	        ByteArrayOutputStream stream = new ByteArrayOutputStream();
	        bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
	        byte [] byte_arr = stream.toByteArray();
	        String image_str = Base64.encodeBytes(byte_arr);
	        ArrayList<NameValuePair> nameValuePairs = new  ArrayList<NameValuePair>();

	        nameValuePairs.add(new BasicNameValuePair("image",image_str));

	         Thread t = new Thread(new Runnable() {
			
			@Override
			public void run() {
				  try{
			             HttpClient httpclient = new DefaultHttpClient();
			             HttpPost httppost = new HttpPost("http://10.0.2.2/Upload_image_ANDROID/upload_image.php");
			             httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			             HttpResponse response = httpclient.execute(httppost);
			             String the_string_response = convertResponseToString(response);
			             runOnUiThread(new Runnable() {
				      			
				      			@Override
				      			public void run() {
				      				Toast.makeText(UploadImage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();		      				
				      			}
				      		});
			             
			         }catch(Exception e){
			        	  runOnUiThread(new Runnable() {
			      			
			      			@Override
			      			public void run() {
			      				Toast.makeText(UploadImage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();			      				
			      			}
			      		});
			               System.out.println("Error in http connection "+e.toString());
			         }	
			}
		});
         t.start();
	    }

	    public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{

	    	 String res = "";
	    	 StringBuffer buffer = new StringBuffer();
	    	 inputStream = response.getEntity().getContent();
             int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
              runOnUiThread(new Runnable() {
   			
   			@Override
   			public void run() {
   				Toast.makeText(UploadImage.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();	      				
   			}
   		});
         
             if (contentLength < 0){
             }
             else{
	                byte[] data = new byte[512];
	                int len = 0;
	                try
	                {
		                while (-1 != (len = inputStream.read(data)) )
		                {
		                	buffer.append(new String(data, 0, len)); //converting to string and appending  to stringbuffer…..
		                }
	                }
	                catch (IOException e)
	                {
	                	e.printStackTrace();
	                }
	                try
	                {
	                	inputStream.close(); // closing the stream…..
	                }
	                catch (IOException e)
	                {
	                	e.printStackTrace();
	                }
	                res = buffer.toString();	 // converting stringbuffer to string…..

	                runOnUiThread(new Runnable() {
           			
           			@Override
           			public void run() {
           			   Toast.makeText(UploadImage.this, "Result : " + res, Toast.LENGTH_LONG).show();
           			}
           		});
	                //System.out.println("Response => " +  EntityUtils.toString(response.getEntity()));
             }
	         return res;
	    }
}

Note : You should do networks operations inside a thread only.
AND you cannot modify UI elements inside a thread, but you have to do inside a UIThread only.

Now download a file from here which encodeBytes in Base64 Format. Put this file in the same package of UploadImage.java. See the screenshot.

Upload Image

Upload Image

However you can put in your own package but don’t forget to change the package name otherwise you will get error.

Now the server part.

Create a folder named Upload_image_ANDROID in your htdocs folder and inside that create a file named upload_image.php and copy this code into it.

I am saying the htdocs folder because I am using XAMPP. You change this according to your use.

<?php
	$base=$_REQUEST['image'];
	 $binary=base64_decode($base);
	header('Content-Type: bitmap; charset=utf-8');
	$file = fopen('uploaded_image.jpg', 'wb');
	fwrite($file, $binary);
	fclose($file);
	echo 'Image upload complete!!, Please check your php file directory……';
?>

Now run your program and check the folder in which your php file resides.
Note: Make sure your server is running.
Here I am uploading the icon image itself.

If you want to upload another file in your SDCARD you have to change this line to give the exact path

Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon);

For example if I have to upload a file residing in my SDCARD I would change the path like this.

Bitmap bitmap = BitmapFactory.decodeFile(“/sdcard/android.jpg”);

This tutorial explains how to create an SDCARD and start the emulator with the SDCARD
and this tutorial explains how to put file inside your emulator SDCARD

if you want to use the android using php and mysql
please check these posts.

1. Android phpMysql connection
2. Android phpmySQL connection redone.

Please comment if you didn’t get it right or you like this post.