Upload Files Using JSP and Servlet

File Upload with Servlet 3.0 

This code works on Glassfish 3.

This is a simple example of how to upload files using JSP and Servlet 3.0 which is a part of Java EE 6. While in earlier versions of Servlets we had to use commons fileupload or other libraries, this feature has been integrated into the Servlet 3.0 specification. Here is the code for a simple servlet and a JSP file that makes a file upload request to the servlet.

1.) FileUploadServlet.java

package com.blogspot.aoj.servlet3;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.log4j.Logger;

@WebServlet(urlPatterns = "/fileUpload")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
  private static Logger logger = Logger.getLogger(FileUploadServlet.class);

  public FileUploadServlet() {
    super();
  }

  protected void doGet(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException {
    for (Part part : request.getParts()) {
      logger.info(part.getName());
      InputStream is = request.getPart(part.getName()).getInputStream();
      int i = is.available();
      byte[] b = new byte[i];
      is.read(b);
      logger.info("Length : " + b.length);
      String fileName = getFileName(part);
      logger.info("File name : " + fileName);
      FileOutputStream os = new FileOutputStream("c:/temp/logs/" + fileName);
      os.write(b);
      is.close();
    }

  }

  private String getFileName(Part part) {
    String partHeader = part.getHeader("content-disposition");
    logger.info("Part Header = " + partHeader);
    for (String cd : part.getHeader("content-disposition").split(";")) {
      if (cd.trim().startsWith("filename")) {
        return cd.substring(cd.indexOf('=') + 1).trim()
            .replace("\"", "");
      }
    }
    return null;

  }

  protected void doPost(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
  }

}

Note:

There is no need to use a deployment descriptor the @WebServlet annotation is enough, which uses the urlPatterns property to define servlet mappings.

The @MultipartConfig is used to indicate that the servlet expects requests wof multipart/form-data MIME type which is required for file upload. Using @MultipartConfig allows you to use the request.getParts get the parts of the request.

The getFileName method gets the file name from the content-disposition header.
 

2.) upload.jsp

<html>
<head>
<title>File Upload with Servlet 3.0</title>
</head>
<body>
<form action="fileUpload" enctype="multipart/form-data" method="post">
<input type="file" name="uploadFile" /> <input type="submit" /></form>
</body>
</html>

Java Tips

See also
Important Servlet Questions

Do you have a Java Problem?
Ask It in The Java Forum

Java Books
Java Certification, Programming, JavaBean and Object Oriented Reference Books

Return to : Java Programming Hints and Tips

All the site contents are Copyright © www.erpgreat.com and the content authors. All rights reserved.
All product names are trademarks of their respective companies.
The site www.erpgreat.com is not affiliated with or endorsed by any company listed at this site.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
 The content on this site may not be reproduced or redistributed without the express written permission of
www.erpgreat.com or the content authors.