Upload file into server - JSP Program

Q. Write a JSP program to upload the file into the server.

Answer:

JSP can be used with HTML form tag to upload file to the server. There are multiple ways to upload the file to the server. We are using MultipartRequest class. It is utility class to handle the multipart/form-data request.

In this example, we are creating two files index.html and upload.jsp. The HTML must have the "post" methods and encrypt type should be multipart/form-data. For running this application, we must have the latest version of commons-fileupload.x.x.jar and commons-io-x.x.jar file.

index.html

<html>
    <head>
        <title>File Uploading Form</title>
    </head>
    <body>
        <form action="upload.jsp" method="post" enctype="multipart/form-data">
            <fieldset style="width:20%; background-color: #e6ff99">
                <h2>File Upload Example</h2>
                <hr>
                Select a file to upload: <br /><br />
                <input type="file" name="file" size="50" />
                <br /><br />
                <input type="submit" value="Upload File" />
            </fieldset>
        </form>
    </body>
</html>


upload.jsp

<%@ page import="java.io.*,java.util.*, javax.servlet.*" %>
<%@ page import="javax.servlet.http.*" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<%@ page import="org.apache.commons.io.output.*" %>

<%
    File file ;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    ServletContext context = pageContext.getServletContext();
    String filePath = context.getInitParameter("file-upload");

    // Verify the content type
    String contentType = request.getContentType();
    if ((contentType.indexOf("multipart/form-data") >= 0))
    {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(maxMemSize);
        // Location to save data that is larger than maxMemSize.
        factory.setRepository(new File("D:\\temp"));

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum file size to be uploaded.
        upload.setSizeMax( maxFileSize );
        try
        {
             // Parse the request to get file items.
             List fileItems = upload.parseRequest(request);

             // Process the uploaded file items
             Iterator i = fileItems.iterator();

             out.println("<html>");
             out.println("<head>");
             out.println("<title>JSP File upload</title>");  
             out.println("</head>");
             out.println("<body>");
             while ( i.hasNext () )
             {
                FileItem fi = (FileItem)i.next();
                if ( !fi.isFormField () )
                {
                    // Get the uploaded file parameters
                    String fieldName = fi.getFieldName();
                    String fileName = fi.getName();
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();
                    // Write the file
                    if( fileName.lastIndexOf("\\") >= 0 )
                    {
                        file = new File( filePath +
                        fileName.substring( fileName.lastIndexOf("\\"))) ;
                    }
                    else
                    {
                        file = new File( filePath +
                        fileName.substring(fileName.lastIndexOf("\\")+1)) ;
                    }
                    fi.write( file ) ;
                    out.println("Uploaded Filename: " + filePath +
                    fileName + "<br>");
                }
            }
            out.println("</body>");
            out.println("</html>");
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
    else
    {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");  
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
    }
%>


web.xml

<web-app>
    <context-param>
        <description>Location to store uploaded file</description>
        <param-name>file-upload</param-name>
        <param-value>
            D:\TOMCAT_HOME_6\apache-tomcat-6.0.48\webapps\data\
        </param-value>
    </context-param>
    <servlet>
        <servlet-name>xyz</servlet-name>
        <jsp-file>/index.html</jsp-file>
    </servlet>
    <servlet-mapping>
        <servlet-name>xyz</servlet-name>
        <url-pattern>/test</url-pattern>
    </servlet-mapping>
</web-app>


Output:

file upload

After successful upload of file, it displays the location of the uploaded file.
Uploaded Filename: D:\TOMCAT_HOME_6\apache-tomcat-6.0.48\webapps\data\employee.jpg