Quantcast
Channel: Fileinputstream – MOBILE PROGRAMMING
Viewing all articles
Browse latest Browse all 12

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

$
0
0

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.


Viewing all articles
Browse latest Browse all 12

Trending Articles