Friday, June 23, 2006

File Uploading

Documentation:

File uploading Code and needed software

Website: http://jakarta.apache.org/commons/fileupload/

(1)commons-fileupload-1.1.jar
(2)commons-io-1.1.jar

Form Page Code - that's used to upload content to the server.


form action="GetFile.jsp" method="post" enctype="multipart/form-data">
input name="fname" type="file">
input value="Upload" type="submit">
/form>


Here "ENCTYPE" attribute specifies the content type used to submit the form to the server. The value "multipart/form-data" should be used in combination with the INPUT element, type="file".



<%@ page import="java.util.* , java.io.* , org.apache.commons.fileupload.* , org.apache.commons.fileupload.servlet.* , org.apache.commons.fileupload.disk.* " %>



<%
if( FileUpload.isMultipartContent( request ) ) {

FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
System.out.println("Before Parsing");
upload.setSizeMax(10485760); // 10 MB in byte representation.
List items = null;

try{
items = upload.parseRequest(request);

System.out.println("After Parsing");

Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();

String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long fileSize = item.getSize();

System.out.println(" Field name from uploading page: " + fieldName);
System.out.println(" File name along with path: " + fileName);
System.out.println(" Content type: " + contentType);
System.out.println(" Is in the bytes: " + isInMemory);
System.out.println(" File size: " + fileSize);

if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString();
} else {
System.out.println("Uploading File");

String dirName = "c:\\" + fileName;
File uploadedFile = new File( dirName );
item.write(uploadedFile);
}
}

}catch(FileUploadException ex){
System.out.println("FileUploadException: " + ex.getMessage());
}

if(items==null) {
%>

You are limited to upload file size upto 10 MB only


<%
} else{

%>

File Uploaded Successfully.


<%
}
}
%>


Notes:

File Uploading using Jakarta Commons.
http://terminalxeption.com/?&blogid=1

Reference:
http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=50&t=010325


Issues:

(1) Browser issue

String fileName = item.getName();

From API:

Returns the original filename in the client's filesystem, as provided by the browser (or other client software). In most cases, this will be the base file name, without path information. However, some clients, such as the Opera, IE browsers, do include path information.