WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JSP file upload


JSP can be used with the HTML form tag to allow users to upload files to the server. The uploaded file can be a text file or an image file or any document.

In this chapter, we use Servlet to process file uploads. The files used are:

  • upload.jsp : File upload form.
  • message.jsp : Jumps to the page after the upload is successful.
  • UploadServlet.java : Upload processing Servlet.
  • The jar files to be imported: commons-fileupload-1.3.2, commons-io-2.5.jar.

Next we will introduce in detail.


Create a file upload form

The HTML code below creates a file upload form. The following points need to be noted:

  • The form method property should be set to the POST method, not the GET method.
  • The form enctype attribute should be set to multipart/form-data.
  • The form action property should be set to the servlet file that handles file uploads on the backend server. The following example uses the UploadServlet servlet to upload files.
  • Upload a single file, you should use a single attribute with the attribute type="file" <input .../> label. In order to allow multiple file uploads, include multiple input tags with different name attribute values. The input tag has a different value for the name attribute. The browser will associate a browse button for each input tag.

upload.jsp The file code is as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File upload example - tutorial</title>
</head>
<body>
<h1>File upload example - tutorial</h1>
<form method="post" action="/TomcatTest/UploadServlet" enctype="multipart/form-data">
    Select a file:
    <input type="file" name="uploadFile" />
    <br/><br/>
    <input type="submit" value="Upload" />
</form>
</body>
</html>

Write a background servlet

The following is the source code of the UploadServlet, which is the same as processing the file upload. Before we do this, we must ensure that the dependency package has been imported into the WEB-INF/lib directory of the project:

You can directly download the two dependencies provided by this site:

The source code for the UploadServlet is as follows:

package com.welookups.test;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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;
 

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
     
    // Upload file storage directory
    private static final String UPLOAD_DIRECTORY = "upload";
 
    // Upload configuration
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB
 
    /**
* Upload data and save files
     */
    protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
        // Check if it is a multimedia upload
        if (!ServletFileUpload.isMultipartContent(request)) {
            // If not, stop
            PrintWriter writer = response.getWriter();
            writer.println("Error: Form must contain enctype=multipart/form-data");
            writer.flush();
            return;
        }
 
        // Configure upload parameters
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Set memory threshold - when exceeded, a temporary file will be generated and stored in a temporary directory
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // Set up a temporary storage directory
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
 
        ServletFileUpload upload = new ServletFileUpload(factory);
         
        // Set the maximum file upload value
        upload.setFileSizeMax(MAX_FILE_SIZE);
         
        // Set the maximum request value (including file and form data))
        upload.setSizeMax(MAX_REQUEST_SIZE);
        
        // Chinese processing
        upload.setHeaderEncoding("UTF-8"); 

        // Construct a temporary path to store the uploaded file
        // This path is relative to the current application directory
        String uploadPath = getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY;
       
         
        // Create if the directory does not exist
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
 
        try {
            // Parse the requested content to extract file data
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);
 
            if (formItems != null && formItems.size() > 0) {
                // Iterating form data
                for (FileItem item : formItems) {
                    // Handling fields that are not in the form
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);
                        // The upload path of the output file in the console
                        System.out.println(filePath);
                        // Save file to hard drive
                        item.write(storeFile);
                        request.setAttribute("message",
                            "File upload succeeded!");
                    }
                }
            }
        } catch (Exception ex) {
            request.setAttribute("message",
                    "Error message: " + ex.getMessage());
        }
        // redirect to message.jsp
        getServletContext().getRequestDispatcher("/message.jsp").forward(
                request, response);
    }
}

message.jsp The file code is as follows´╝Ü

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File upload result</title>
</head>
<body>
    <center>
        <h2>${message}</h2>
    </center>
</body>
</html>

Compile and run the Servlet

Compile the Servlet UploadServlet above and create the required entries in the web.xml file as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
  <servlet>
    <display-name>UploadServlet</display-name>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>com.welookups.test.UploadServlet</servlet-class>
  </servlet>
   
  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/TomcatTest/UploadServlet</url-pattern>
  </servlet-mapping>
</web-app>

Try now to upload the file using the HTML form you created above. When you visit http://localhost:8080/TomcatTest/upload.jsp in your browser, the demo looks like this: