In servlets, there is a provision to upload files in the server just through the browser. So we will have an html which will have an upload file option and on clicking submit button it uploads the file into the server.
Let’s look at the below HTML.
<html>
<head>
<title>Uploading file through Servlet</title>
</head>
<body>
<h3><b>Upload file:</b></h3>
<b>Select files to Upload</b>: <br />
<form action = "UploadFileServlet" method = "post" enctype = "multipart/form-data">
<input type = "file" name = "file" size = "100" />
<br /> <br /> <br />
<input type = "submit" value = "Upload Files" />
</form>
</body>
</html>
As seen above, these are the points which we need to note.
- The form method should be set to post as it would be a file upload.
- The form enctype attribute should be set to multipart/form-data as we would upload a file.
- The action attribute should have the name of the servlet which would handle the request and help with the upload.
- Once submit button is clicked, the file would be uploaded.

This is how the HTML would look as seen above.
Now let’s look at the servlet implementation. To implement, we need some external jars related to upload fo file.
commons-io-x.x.jar & commons-fileupload.x.x.jar which has the depedencies.
Let’s look at the code implementation.
import java.io.*;
import java.util.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.*;
public class UploadFileServlet extends HttpServlet {
private boolean isMultiReq;
private File file;
private String filePath;
private int maxFileSize = 1024 * 100;
private int maxMemSize = 4 * 1024;
//Init method to get the file path from servlet context defined in web.xml
public void init( ){
System.out.println("Init called");
filePath = getServletContext().getInitParameter("file-path");
}
//Post method to handle file upload request
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
//To check whether the request is multipart i.e; kind of file upload
isMultiReq = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
if( !isMultiReq ) {
System.out.println("No file upload req found \n");
out.println("<html>");
out.println("<head>");
out.println("<title>Upload Using Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<p><b>No files were uploaded</b></p>");
out.println("</body>");
out.println("</html>");
return;
}
System.out.println("file upload req found. Processing the same. \n");
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:\\project\temp"));
// New file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax(maxFileSize);
System.out.println("Upload handler and factory is set");
try {
// Parse the request to get list of file objects.
System.out.println("Parsing the list of file items");
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator fi = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
while (fi.hasNext()) {
FileItem f = (FileItem)fi.next();
if ( !f.isFormField () ) {
// Get the uploaded file parameters
String fileName = f.getName();
String contentType = f.getContentType();
boolean isInMemory = f.isInMemory();
// 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)) ;
}
f.write(file) ;
out.println("<b>Uploaded Filename</b>: " + fileName + "<br>");
}
}
out.println("</body>");
out.println("</html>");
} catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
throw new ServletException("GET method used with " +
getClass( ).getName( )+": POST method required.");
}
}
}
As seen in the init method, we are getting the file path from the servlet context. Let’s see how it is defined there.
<web-app>
....
<context-param>
<description>File path to store uploaded file</description>
<param-name>file-path</param-name>
<param-value>
C:\tomcat\webapps\files\
</param-value>
</context-param>
....
</web-app>
As seen above, the param file-path is defined with the appropriate param value. Same is fetched in the init method.
Below is the servlet mapping.
<servlet> <servlet-name>UploadServletExample</servlet-name> <servlet-class>UploadFileServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServletExample</servlet-name> <url-pattern>/UploadFileServlet</url-pattern> </servlet-mapping>