RSS

How to upload file on server?

24 Jan

Do some simple steps:
Step 1:
Create class HttpFileUpload as shown below.

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.util.Log;

public class HttpFileUpload implements Runnable{

	URL connectURL;
	String responseString;
	String Title;
	String Description;
	byte[ ] dataToServer;
	FileInputStream fileInputStream = null;

	HttpFileUpload(String urlString, String vTitle, String vDesc){
		try{
			connectURL = new URL(urlString);
			Title= vTitle;
			Description = vDesc;
		}catch(Exception ex){
			Log.i("HttpFileUpload","URL Malformatted");
		}
	}

	void Send_Now(FileInputStream fStream){
		fileInputStream = fStream;
		Sending();
	}

	void Sending(){
		String iFileName = "DSC_0061.jpg";
		String lineEnd = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		String Tag="fSnd";
		try
		{
			Log.e(Tag,"Starting Http File Sending to URL");

			// Open a HTTP connection to the URL
			HttpURLConnection conn = (HttpURLConnection)connectURL.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);

			DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

			dos.writeBytes(twoHyphens + boundary + lineEnd);
			dos.writeBytes("Content-Disposition: form-data; name=\"title\""+ lineEnd);
			dos.writeBytes(lineEnd);
			dos.writeBytes(Title);
			dos.writeBytes(lineEnd);
			dos.writeBytes(twoHyphens + boundary + lineEnd);

			dos.writeBytes("Content-Disposition: form-data; name=\"description\""+ lineEnd);
			dos.writeBytes(lineEnd);
			dos.writeBytes(Description);
			dos.writeBytes(lineEnd);
			dos.writeBytes(twoHyphens + boundary + lineEnd);

			dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + iFileName +"\"" + lineEnd);
			dos.writeBytes(lineEnd);

			Log.e(Tag,"Headers are written");

			// create a buffer of maximum size
			int bytesAvailable = fileInputStream.available();

			int maxBufferSize = 1024;
			int bufferSize = Math.min(bytesAvailable, maxBufferSize);
			byte[ ] buffer = new byte[bufferSize];

			// read file and write it into form...
			int 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);
			}
			dos.writeBytes(lineEnd);
			dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

			// close streams
			fileInputStream.close();

			dos.flush();

			Log.e(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode()));

			InputStream is = conn.getInputStream();

			// retrieve the response from server
			int ch;

			StringBuffer b =new StringBuffer();
			while( ( ch = is.read() ) != -1 ){ b.append( (char)ch ); }
			String s=b.toString();
			Log.i("Response",s);
			dos.close();
		}
		catch (MalformedURLException ex)
		{
			Log.e(Tag, "URL error: " + ex.getMessage(), ex);
		}

		catch (IOException ioe)
		{
			Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
		}
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
	}
}

Step 2:
create function UploadFile() as shown below. By using this function we are passing only the required data to HttpFileUpload class which will upload file that you want.

public void UploadFile(){
		try {
			// Set your file path here
			FileInputStream fileInputStream = new FileInputStream(new File("/mnt/sdcard/DCIM/100ANDRO/DSC_0061.jpg"));

			// Set your server page url (and the file title/description)
			HttpFileUpload httpFileUpload = new HttpFileUpload("http://100.111.0.125/UploadServiceTest/Default.aspx", "my file title","my file description");

			httpFileUpload.Send_Now(fileInputStream);

		} catch (FileNotFoundException e) {
			e.toString();
		}
	}
Advertisements
 
2 Comments

Posted by on January 24, 2013 in Android Source Code

 

2 responses to “How to upload file on server?

  1. lpyenucom12

    December 22, 2015 at 4:48 AM

    Hi..this is a great tutorial…
    How should i get the file from server to andriod?

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: