Open In App

JSP – File Uploading

Last Updated : 17 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn about how to upload a file to a server using JSP. JSP stands for Java Server Pages. JSP is a server-side web technology, traditionally used to create dynamic web pages. Before that, servlets were highly used to create dynamic web pages, in that HTML tags are inserted into the Java code(in particular response print stream). However, it will be tedious to write a lot of HTML tags into every method of response stream, to reduce the amount of code to be written when JSPs are created. In JSPs, Java code is written into HTML pages to produce dynamic pages. In general, JSP works exactly like a servlet, but we don’t have to create a servlet class to return a dynamic web response.

We will see how we can implement the file upload functionality in two different approaches.

Prerequisite of Topic

  • Java – Knowledge of Core Java.
  • JSP & Servlets – basic concepts.
  • Eclipse & Maven.

Project Structure:

Project Structure JSP File Uploading

Initial Setup for Implementation

Before starting off, there are some common steps to be done before both implementations.
Step 1: Create a Maven starter Web App project in Eclipse IDE, go to New -> Maven Project and select web app type.
Step 2: Open your pom.xml, add the required dependencies and the necessary plugin configurations given below.

XML




    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>JspFileUpload</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <dependencies>
        <dependency>
            <groupId>com.servlets</groupId>
            <artifactId>cos</artifactId>
            <version>09May2002</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.5</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.15.0</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <release>17</release>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.3</version>
            </plugin>
        </plugins>
    </build>
</project>


Step 3: Now we need to create an index page that provides two forms to call the different implementations.

Step 4: Right click on the webapp folder and go to new -> jsp file to create a new index.jsp page.

Step 5: Create two forms in that index.jsp like the given code, make sure you are using the POST request and encoding type as MULTIPART/FORM-DATA to send the file.

Step 6: Each forms will have two different action url to call the required implementations.

HTML




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>File Upload</title>
<style>
body {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100vh;
    margin: 0;
    font-family: sans-serif;
}
  
h1 {
    color: #308d46;
}
  
.uploadButton {
    padding: 10px 20px;
    font-size: 16px;
    background-color: #007bff;
    color: #fff;
    border: none;
    cursor: pointer;
}
  
.row {
    margin: 10px 0;
}
</style>
</head>
<body>
    <h1>GeeksForGeeks</h1>
    <h3>Upload using Apache Commons File Upload</h3>
    <form action="commonsfileupload.jsp" method="post"
        enctype="multipart/form-data">
        <div class="row">
            <input type="file" name="file1" required>
        </div>
        <div class="row">
            <button class="uploadButton">Upload File</button>
        </div>
    </form>
    <h3>Upload using Multipart Request</h3>
    <form action="multipartrequest.jsp" method="post"
        enctype="multipart/form-data">
        <div class="row">
            <input type="file" name="file2" required>
        </div>
        <div class="row">
            <button class="uploadButton">Upload File</button>
        </div>
    </form>
  
</body>
</html>


Now that we have done with the initial configuration that is common to the below approaches.

Start your tomcat server and deploy your app to see the initial welcome screen with two forms like below.

intial_forms_jsp_file_uploading

Approach 1:

In this approach, we will use the commons-fileupload and commons-io libraries provided by apache.org to parse the HTTP request and store it under the local file system.

Step 1: Create a jsp file under webapp folder named commonsfileupload.jsp to handle the request.

Step 2: In that file, enter the below code to make it work for receiving the request along with the file and saving it in the local file system.

HTML




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import="java.io.*,java.util.*, javax.servlet.*"%>
<%@ 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.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <%
    File file;
    // maximum file size allowed
    // representing 5 Mega Bytes.
    int maxFileSize = 5000 * 1024;
    // maximum memory allocated to store the file
    // from request for further processing
    int maxMemSize = 5000 * 1024;
    // file path to store the uploaded files
    String filePath = "d:/file-data/";
  
    // checking whethe multipart formdata is used
    // as request encoding type
    String contentType = request.getContentType();
  
    if (contentType.indexOf("multipart/form-data") != -1) {
  
        try {
            // creating factory object from commons fileupload
               // to store the object
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // if the file is larger than memory size store it in tmp directory
            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(repository);
  
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
  
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);
            // Parse the request to get file items.
            List<FileItem> fileItems = upload.parseRequest(request);
  
            // Process the uploaded file items
            Iterator<FileItem> 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 = 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
                    file = new File(filePath + fileName);
                    fi.write(file);
                    out.println("Uploaded Filename: " + filePath + fileName + "<br>");
                }
            }
            out.println("</body>");
            out.println("</html>");
        } catch (Exception ex) {
            out.println(ex.getMessage());
            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>");
    }
    %>
</body>
</html>


Step 3: Once the jsp file is done, install the webapp in your tomcat server and start the server.

Output of Commons File Upload:

final_output_commons_file_upload

Approach 2:

In this approach, we will use the Oreilly servlet library to parse our request object to get the file. After parsing the file using the MultipartRequest object, it will store the file in the given location in the constructor argument.

Step 1: Create a jsp file under webapp folder named multipartrequest.jsp.

Step 2: In that file, enter the below code to make it work for receiving the request along with the file and saving it in the local file system.

HTML




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import="com.oreilly.servlet.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
// Uses MultipartRequest from oreilly library.
// accepts request object and the target location to save
MultipartRequest m = new MultipartRequest(request, "d:/file-data");
out.println("<h1>File uploaded successfully</h1>");
%>
</body>
</html>


Step 3: Once the jsp file is done, install the webapp in your tomcat server and start the server.

Output of Multi Part Request:

final_output_multipartrequest



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads