Site icon DataFlair

JSP File Uploading to the Server

FREE Online Courses: Dive into Knowledge for Free. Learn More!

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.

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

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:

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:

Output:

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.

Exit mobile version