18 December 2009

file upload using servlet

Hi friends
Here is the example to upload a file using java servlet technology.

<form action="http://your_host/servlet/UploadServlet?your_config" enctype="multipart/form-data" method="post">

<td> <input name="fname" size="20" type="file" /> </td>
<td> <input type="Submit" value="Upload" /> </td> </form>



import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;

public class UploadFile extends HttpServlet {

public void doPost(HttpServletRequest req HttpServletResponse res)

FileUpload fup new FileUpload();
boolean isMultipart FileUpload.isMultipartContent(req);
// Create a new file upload handler
DiskFileUpload upload new DiskFileUpload();

// Parse the request
List /* FileItem */ items upload.parseRequest(req);

Iterator iter items.iterator();
while (iter.hasNext()) {

FileItem item (FileItem) iter.next();

if (item.isFormField()) {
System.out.println( its a field );
} else {
System.out.println( its a file );
File cfile new File(item.getName());
File tosave new File(getServletContext().getRealPath( / ) cfile.getName());

}catch(Exception e){System.out.println(e);}

describe servlet in your web.xml file: 



  • Servlet's configuration file can be saved anywhere on your server. i.e. if you are using UploadServlet?config line we assume this file is saved under the root directory of  your servletrunner. 
  • You can use query string for servlet in this form too: 
    This way you can provide a name for the uploaded file right in the query string. This option could be useful if you are generating upload forms (pages) dynamically.