Friday 30 August 2013

How to upload file using Servlet in jsp


 We have to use two jar files

1) commons-fileupload-1.2.2.jar 
2) commons-io-2.3.jar

//-------------------------------  upload.jsp ------------------------------------------

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File Upload</title>
</head>
<body>
<table border="1" >

 <tr>
    <td>
<form method="post" action="UploadServlet" enctype="multipart/form-data">
<input type="file" name="uploadFile" />
<br/><br/> 
<input type="submit" value="Upload" />
</form>
 </td>
</tr>

</table>
</body>
</html>

//-------------------------------- message.jsp ---------------------------------------------


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload file</title>
</head>
<body>
<center>
<h2>${requestScope.message}</h2>
</center>
</body>
</html>

//------------------------------- web.xml -------------------------------------------------

<?xml version="1.0" encoding="UTF-8"?>
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
id="WebApp_ID" version="2.5">
  <display-name>UploadServletApp</display-name>

  <servlet>
    <description></description>
    <display-name>UploadServlet</display-name>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>codejava.upload.UploadServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/UploadServlet</url-pattern>
  </servlet-mapping>
</web-app>

//------------------------------------ UploadServlet.java --------------------------------


package codejava.upload;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadServlet extends HttpServlet
{
  private static final long serialVersionUID = 1L;
  private static final String UPLOAD_DIRECTORY = "upload";
  private static final int THRESHOLD_SIZE = 3145728;
  private static final int MAX_FILE_SIZE = 41943040;
  private static final int MAX_REQUEST_SIZE = 52428800;

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    if (!ServletFileUpload.isMultipartContent(request)) {
      PrintWriter writer = response.getWriter();
      writer.println("Request does not contain upload data");
      writer.flush();
      return;
    }

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(3145728);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(41943040L);
    upload.setSizeMax(52428800L);

    String uploadPath = getServletContext().getRealPath("") + 
      File.separator + "upload";

    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
      uploadDir.mkdir();
    }

    try
    {
      List formItems = upload.parseRequest(request);
      Iterator iter = formItems.iterator();

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

        if (!item.isFormField()) {
          String fileName = new File(item.getName()).getName();
          String filePath = uploadPath + File.separator + fileName;
          File storeFile = new File(filePath);

          item.write(storeFile);
        }
      }
      request.setAttribute("message", "Upload has been done successfully!");
    } catch (Exception ex) {
      request.setAttribute("message", "There was an error: " + ex.getMessage());
    }
    getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
  }
}


No comments:

Post a Comment