Tuesday, May 15, 2007

runtime file upload using java

CLIENT (HttpMultiPartFileUpload.java):

import java.io.File;
import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.MultipartPostMethod;

public class HttpMultiPartFileUpload {
private static String url =
"http://aruljose:9090/ProcessFileUpload.jsp";

public static void main(String[] args) throws IOException {
HttpClient client = new HttpClient();
MultipartPostMethod mPost = new MultipartPostMethod(url);
client.setConnectionTimeout(8000);

// Send any XML file as the body of the POST request
File f1 = new File("C:\\Documents and Settings\\aruljose\\Desktop\\downloaded.jpg");
//File f2 = new File("academy.xml");
//File f3 = new File("academyRules.xml");

System.out.println("File1 Length = " + f1.length());
//System.out.println("File2 Length = " + f2.length());
//System.out.println("File3 Length = " + f3.length());

mPost.addParameter(f1.getName(), f1);
//mPost.addParameter(f2.getName(), f2);
//mPost.addParameter(f3.getName(), f3);

int statusCode1 = client.executeMethod(mPost);

System.out.println("statusLine>>>" + mPost.getStatusLine());
mPost.releaseConnection();
}
}


SERVER (ProcessFileUpload.jsp) :

<%@ page contentType="text/html;charset=windows-1252"%>
<%@ page import="org.apache.commons.fileupload.DiskFileUpload"%>
<%@ page import="org.apache.commons.fileupload.FileItem"%>
<%@ page import="java.util.List"%>
<%@ page import="java.util.Iterator"%>
<%@ page import="java.io.File"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Process File Upload</title>
</head>
<%
System.out.println("Content Type ="+request.getContentType());

DiskFileUpload fu = new DiskFileUpload();
// If file size exceeds, a FileUploadException will be thrown
fu.setSizeMax(1000000);

List fileItems = fu.parseRequest(request);
Iterator itr = fileItems.iterator();

while(itr.hasNext()) {
FileItem fi = (FileItem)itr.next();

//Check if not form field so as to only handle the file inputs
//else condition handles the submit button input
if(!fi.isFormField()) {
System.out.println("\nNAME: "+fi.getName());
System.out.println("SIZE: "+fi.getSize());
//System.out.println(fi.getOutputStream().toString());
File fNew= new File("C:\\Documents and Settings\\aruljose\\Desktop\\downloaded1.jpg");

System.out.println(fNew.getAbsolutePath());
fi.write(fNew);
}
else {
System.out.println("Field ="+fi.getFieldName());
}
}
%>
<body>
Upload Successful!!
</body>
</html>

No comments: