Monday, March 28, 2011

File Upload to server by Servlet(or JSP)

HTML Form
========

<FORM id="upform" name="upform" ENCTYPE='multipart/form-data' action="<URL>" method='POST'>

<INPUT type='file' name='uploadfile'>

<INPUT type='submit' value='upload'>

</FORM>


Needed Lib

===========

commons-fileupload-1.2.2.jar

commons-io-1.4.jar


Needed imports

===============

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileUploadException;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;


Sample Code Segment

===================

//String fileSavePath="/var/uploaded/"; linux

String fileSavePath="c:\uploaded";

if(ServletFileUpload.isMultipartContent(request))

{

ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());

List fileItemsList = null;

try

{

fileItemsList = servletFileUpload.parseRequest(request);

}

catch(FileUploadException e)

{

System.err.println((new StringBuilder()).append("inside uploadUpdateACtion while parsing Exception is [").append(e.getMessage()).append("]").toString());

throw new Exception((new StringBuilder()).append("inside uploadUpdateACtion while parsing Exception is [").append(e.getMessage()).append("]").toString());

}

Iterator iterator = fileItemsList.iterator();

FileItem fi = (FileItem)iterator.next();

String fileName = fi.getName();

fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);

String saveFile = (new StringBuilder()).append(fileSavePath).append(fileName).toString();

if("".equalsIgnoreCase(fileName))

throw new Exception("Please choose file to upload");

try

{

fi.write(new File(saveFile));

}

catch(Exception e)

{

System.err.println((new StringBuilder()).append("inside uploadUpdateACtion while writing the uploded file Exception is [").append(e.getMessage()).append("]").toString());

throw new Exception((new StringBuilder()).append("inside uploadUpdateACtion while writing the uploded file Exception is [").append(e.getMessage()).append("]").toString());

}




}

No comments: