Wednesday, 16 October 2013

How to upload file using jsp and servlet

Leave a Comment
In this tutorial i will like to show how to upload file in jsp page and servlet.

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

*JSTL 1.1 library is in global libraries.(Im 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



By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

0 comments:

Post a Comment

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.