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.
- The attribute of the form method must be set to POST.
- The encrypt attribute of the form must be set to multipart/form-data.
- 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.
- You can use the <input…/> tag to upload a single file.
- 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:
- The code below depends upon FileUpload so you should have its latest version.
- FileUpload depends on common IO so make sure to have its latest version downloaded.
- As you are testing now you should put a file of less size as compared to maxsize.
- 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
-
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.
-
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.
-
What are some advantages of using JSP?
These pages can be combined with servlets. JSP supports both element-based and scripting-based dynamic content.
-
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.