How to upload file using JSP and Servlet

In this tutorial, I will like to share how to upload file on JSP page and servlet.

Note: Please add JSTL1.1 library and Apache Common FileUpload

*JSTL 1.1 library is in global libraries. (I'm using Netbean 7.3.1)

JSP file

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Upload page - servlet</title>
    </head>
    <body>
        <h1>Upload file JSP!</h1>
        ${uploadMessage}
        <br/>
        <form action="<c:url value="/uploadservlet" />" method="post" enctype="multipart/form-data">
            <input type="file" id="FUploadDoc" name="afile" size="50" />
            <input type="submit" name="bUpload" value="upload file"/>
        </form>
    </body>
</html>

web.xml Configuration

 <servlet>
        <servlet-name>uploadservlet</servlet-name>
        <servlet-class>sys.servlet.uploadservlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>uploadservlet</servlet-name>
        <url-pattern>/uploadservlet</url-pattern>
    </servlet-mapping>

The Servlet

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.Part;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@MultipartConfig
@SuppressWarnings("unchecked")
public class uploadservlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       
        response.setContentType("text/html;charset=UTF-8");
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
       
        if (isMultipart) {
            File file = null;
            int maxFileSize = 50000 * 1024;
            int maxMemSize = 50000 * 1024;
            boolean configExist = false;   

            // Verify the content type
            String contentType = request.getContentType();
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(maxMemSize); // maximum size that will be stored in memory
            factory.setRepository(new File("C:/DataUpload/"));
           
            String workingDir = "C:/DataUpload/";  
            ProcessUpload(file, factory, maxFileSize,request,workingDir);

        }else{
            request.setAttribute("uploadMessage", "upload form must be in multipart");
        }
        //redirect back to upload page
        request.getRequestDispatcher("/UploadPage.jsp").forward(request, response);
    }

    
    public void ProcessUpload(File file, DiskFileItemFactory factory, int maxFileSize,
            HttpServletRequest request,String UploadPath) {
       
        ServletFileUpload upload = new ServletFileUpload(factory); // Create a new file upload handler
        upload.setSizeMax(maxFileSize); // maximum file size to be uploaded.
        String Msg = "";
        boolean fileHaveContent = false;
        try {
                 
            String contentType = request.getContentType();
            if ((contentType.indexOf("multipart/form-data") >= 0)) {
               
                if(!new File(UploadPath).exists()){
                    new File(UploadPath).mkdir();
                }  

                //upload using stream
                Part uploadFile = request.getPart("afile");
                String fileName = getFileName(uploadFile);
                OutputStream out = null;
                InputStream filecontent = null;
                out = new FileOutputStream(new File(UploadPath + File.separator
                        + fileName));
                filecontent = uploadFile.getInputStream();
               
                int read = 0;
                final byte[] bytes = new byte[1024];

                while ((read = filecontent.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                }
               
                Msg += "New file (" + fileName + ") created at " + UploadPath;
                out.close();
                filecontent.close();
                fileHaveContent = true;

            } else {
                Msg = "No File Upload";
               
            }
            request.setAttribute("uploadMessage", Msg);
           
        } catch (Exception ex) {
            request.setAttribute("uploadMessage", ex.getMessage());
        }
    }

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

        //means user use Browser IE to upload file, So the above method will not work. This will handle
        //for user using browser IE to upload file
        if(FileName.contains(":")){
            String[] FileNameArr = FileName.split("\\\\");
            FileName = FileNameArr[FileNameArr.length - 1];
        }
        return FileName;
    }

}

Output

  • Before Upload
  • After upload finish


Popular posts from this blog

Example to disable save as certain file type in SSRS Report Viewer

How to create DataGrid or GridView in JSP - Servlet

Control Webpart Visible/Enable using macro in Kentico