Saturday, September 3, 2011

Posting multupart mime to tomcat with no need for external jars

This Class will upload multipart mime to any server via android without the need to any external jars (your app will be smaller in size), it was tested with tomcat 6.
To use it just call:


FileUploader vidUploader = new FileUploader("http://:8080/servlet/UploadMediaFile", "/sdcard/file.mp4");
vidUploader.run();


///////////////////////////////////////////////////////////// FileUploader Class ///////////////////////////////////

package test;

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

import android.content.Context;
import android.os.Process;
import android.util.Log;

public class FileUploader implements Runnable {

URL connectURL;

String responseString;
String fileName;
byte[] dataToServer;
FileInputStream fileInputStream = null;

String lineEnd = "\r\n";
String twoHyphens = "--";

String boundary = "---------------------------239413274531762";




public FileUploader(String urlString, String fileName ){
try{
connectURL = new URL(urlString);

}catch(Exception ex){
Log.e(Prefs.TAG, "MALFORMATED URL");
}
this.fileName = fileName;


}





public void run() {
Log.d(Prefs.TAG, "Upload Thread Started.");
// Lower thread priority a little. We're not the UI.
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

try {
fileInputStream = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
Log.e(Prefs.TAG, e.getMessage());
}
postFile(fileType);

System.out.println("Upload Thread ended.");
}



private void writeHeader(DataOutputStream dos, String name, String value) throws IOException {
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"");
dos.writeBytes(lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(value);
dos.writeBytes(lineEnd);
}


void postFile(int uploadFileType){

try
{
//------------------ CLIENT REQUEST


// 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() );

writeHeader(dos, "media-type-id", "6");
writeHeader(dos, "media-file-id", "2510");
writeHeader(dos, "camera-id", "5");
writeHeader(dos, "user-name", "android-tablet-api-user");
writeHeader(dos, "password", "g7h0Kms5@q#54");
writeHeader(dos, "user-id", "98");


dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"media-file-data\"; filename=\"" + mediaFileName + "\"");
dos.writeBytes(lineEnd);
dos.writeBytes("Content-Type: video/mp4");
dos.writeBytes(lineEnd);
dos.writeBytes(lineEnd);

System.out.println("Headers are written");

// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 8192;
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);
}

// send multipart form data necesssary after file data...

dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes(lineEnd);

// more headers


// close streams
Log.d(Prefs.TAG, "File is written");
fileInputStream.close();
dos.flush();

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.d(Prefs.TAG, "Response: " + s);
dos.close();


}
catch (MalformedURLException ex)
{
Log.e(Prefs.TAG, ex.getMessage());
}

catch (IOException ioe)
{
Log.e(Prefs.TAG, ioe.getMessage());
}
}
}

No comments:

Post a Comment