JSP File Uploading to the Server

FREE Online Courses: Your Passport to Excellence - Start Now

Using the functionality of uploading a file, a user can upload multiple files at the server-side. HTML, along with JSP, is used for this. The file can be a text file, image, binary file, or any document.

JSP File Uploading

File Uploading in JSP

There are two ways to upload a file to the server in JSP:

a) Using third party Jar File – Apache has given a powerful API to upload files. This approach will require two jar files that will be in WEB-INF/lib directory of the application. Download these jar files

  • commons-fileupload.jar
  • commons-io.jar

b) Servlet 3.0 API – Servlet 3.0Specification gives support for uploading files without including any third party APIs.

Let’s understand uploading a file on the server in detail:

Creating an Upload Frontend

Here we use the HTML to create the front end for the uploading of files. Following attributes may be used in the code.

1. action attribute: This attribute will forward the request to another resource.
Syntax:

form action = "UploadForm" 

2. method attribute: This attribute will define the HTTP method that will be used to send form data.
Syntax:

method = "post"

3. enctype attribute: This attribute, using multipart as the value, will allow users to browse and upload multiple files.
Syntax:

enctype = "multipart/form-data

For Example:

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

Some points that need to be understood according to the code above are:

  • The form method should always be POST. The GET method will not be valid here.
  • The form action will contain the name of the JSP file that will support the backend working for the form.
  • The enctype should be properly defined as multipart to browse multiple files
  • To upload one file, you can use a single <input../> tag. To upload multiple files, include various input tags. The name of all input tags should have different values.
  • The browser will generate a new browse button for each new file to be uploaded.

What we created is just a frontend for uploading files. Now we will proceed towards writing the backend of this.

Writing the Backend

Firstly we need to define where the uploaded files will go. One can either set this up in program or it can be programmed in <context-param> of web.xml configuration as following:

<web-app>
....
<context-param>
   <description>Store uploaded file here</description>
   <param-name>file-upload</param-name>
   <param-value>
      c:\apache-tomcat-9.0.34\webapps\data\
   </param-value>
</context-param>
....
</web-app>

Following is the JSP program of uploading the file.

UploadFile.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();
  	// maximum size stored in memory
  	factory.setSizeThreshold(maxMemSize);
  	
  	// Location to save data that is larger than maxMemSize.
  	factory.setRepository(new File("c:\\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>");
   }
%>

Consider the following points before running the above code:

  • Create directories c:\temp and c:\apache-tomcat5.5.29\webapps\data well in advance.
  • Have the latest versions of commons-fileupload.x.x.jar and commons-io-x.x.jar.
  • Upload a file that is less than max file size.

Output:

Uploading file in jsp

When this program is run, the UploadFile.jsp is called, and the file browsed will add to the C:\tomcat 9\root\webapps\data as this is the path we have suggested. You can add any other location as you want on your pc.

Conclusion

In this article, we finally discussed how to do file uploading on the server in JSP. Hope you liked the article and it was useful to you.

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *