Table of contents
1.
Introduction
2.
Uploading files with MultipartRequest class
2.1.
Constructors of MultipartRequest Class
3.
Understanding Uploading in JSP with an Example
3.1.
Creating a File Upload Form
3.2.
Writing Backend JSP Script
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

JSP- File Uploading

Author Naman Kukreja
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Whenever you visit a website, it has some files already uploaded. You can access or sometimes upload some files in the form, so how can you perform all these operations?

We can perform all these operations because of the file uploading feature provided by JSP.

Here the user can perform read and write operations. We will understand this topic in detail while moving further with our article.

Uploading files with MultipartRequest class

There are numerous ways for uploading files to the server, and MultipartRequest is one of them. We can use JSP files with different HTML tags to allow users to upload files to the corresponding servers.

According to requirements, the uploaded file can be of any format like text file, video file, image, and any other format.

You need to have a cos.jar file to use MultipartRtequest. Some points need to be noted before working with MultipartRequest:

Constructors of MultipartRequest Class

  1. MultipartRequest(HttpServletRequest request, String saveDirectory): It is used to upload the files below 1MB of storage.
  2. MultipartRequest(HttpServletRequest request, String saveDirectory, int maxPostSize): We can upload the files up to the specific post size that we have given.
  3. MultipartRequest(HttpServletRequest request, String saveDirectory, int maxPostSize, string encoding): It has the same work as the above one to upload the file with given post size. An additional feature is that it uploads the file with a given encoding.

Understanding Uploading in JSP with an Example

Here, we will create the upload form, and with the help of that, we will discuss file uploading in JSP.

Creating a File Upload Form

Here, we will create the form. With the help of HTML, we will create the uploader form. The form is created by keeping the below points in mind.

  1. The attribute of the form method must be set to POST.
  2. The encrypt attribute of the form must be set to multipart/form-data.
  3. JSP file is handling upload to the backend server, so the form action attribute must be set to the JSP file. Take the uploadfile.jsp in this example.
  4. You can use the  <input…/> tag to upload a single file.
  5. To upload multiple files, use multiple input tags.

The form can be created by the following code:

<html>
   <head>
      <title>File Uploading Form</title>
   </head>
   
   <body>
      <h3>File Upload:</h3>
      Select a file to upload: <br />
      <form action = "UploadServlet" method = "post"
         enctype = "multipart/form-data">
         <input type = "file" name = "file" size = "50" />
         <br />
         <input type = "submit" value = "Upload File" />
      </form>
   </body>
   
</html>

 

The above will give the following output. 

The user can choose the file using choose file button and upload the file afterward.

Writing Backend JSP Script

Now we will define the location where the uploaded file will be stored.

<web-app>
....
<context-param> 
   <description>Location of storage of updated files</description> 
   <param-name>file-upload</param-name> 
   <param-value>
      c:\apache-tomcat-5.5.29\webapps\data\
   </param-value> 
</context-param>
....
</web-app>

 

Following is the source code for your uploadFile.jsp. The following code can handle multiple files uploaded at a time. There are some things that need to be kept in mind before proceeding further these are:

  1. The code below depends upon FileUpload so you should have its latest version.
  2. FileUpload depends on common IO so make sure to have its latest version downloaded.
  3. As you are testing now you should put a file of less size as compared to maxsize.
  4. And make sure to create directories.
<%@ 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)) {
      
      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);
      
DiskFileItemFactory factory = new DiskFileItemFactory();
   
      factory.setSizeThreshold(maxMemSize);
      

 
      factory.setRepository(new File("c:\\temp"));
      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>");
   }
%>

 

You can now try to upload files by using the HTML form you have created above. Directly you can upload any file from your machine. Now when you check the above code's output, you will see this :

You can also read about the JSP Architecture and Lifecycle.

FAQs

  1. Can we upload the file with a size greater than 1MB?
    Yes, you can upload the file but make sure the postsize is greater than 1MB.
     
  2. Can we upload the files in any format?
    yes, we can upload files of any format depending on the types of formats allowed by the administrator.
     
  3. What are some advantages of using JSP?
    These pages can be combined with servlets. JSP supports both element-based and scripting-based dynamic content.
     
  4. What is Java Server Template Engine?
    It is a technology used for separating presentation from processing.

Key Takeaways

In this blog, we have learned why we need the uploading feature, MultipartRequest class, points to be remembered before creating a form, and uploading examples.

JSP may be a new framework for you so if you want to learn more about JSP, mainly how to handle cookies in JSP, then refer to this blog. You will get a complete idea of the cookies structure and how to work with them.

Live masterclass