Servlets - File Uploading

A Servlet can be utilized with a HTML form tag to enable clients to upload documents to the server. A uploaded file could be a text file or picture file or any document.

Creating a File Upload Form

The following HTM code beneath makes an uploader structure. Following are the critical focuses to be noted down −

  • The form method attribute attribute to be set to POST method and GET method can not be used

  • The form enctype ascribe attribute to be set to multipart/form data.

  • The form action attribute attribute to be set to a servlet file which would deal with file uploading at backend server. Following example is utilizing UploadServlet servlet to upload file.

  • To upload a single file you should utilize a single <input .../> tag with property type="file". To permit various files uploading, incorporate more than one info labels with various qualities for the name attribute. The program relates a Browse catch with each of them.




<title>File Uploading Form</title> 



<h3>File Upload:</h3> 

Select a file to transfer: <br /> 

<form action = "UploadServlet" method = "post" enctype = "multipart/form data"> 

<input type = "file" name = "file" size = "50" /> 

<br /> 

<input type = "submit" value = "Upload File" /> 




This will show following outcome which would permit to choose a file from local PC and when client would click at "upload File", form would be submitted alongside the selected fil −


File Upload: 

Select a file to transfer: 

NOTE: This is simply dummy form and would not work.

Writing Backend Servlet

Following is the servlet UploadServlet which would deal with accepting uploaded file and to store it in catalog <Tomcat-establishment directory>/webapps/information. This registry name could likewise be included utilizing an external configuration , for example, a context-param component in web.xml as pursues −




<description>Location to store uploaded file</description> 





</setting param> 



Following is the source code for UploadServlet which can deal with different file uploading at once. Before continuing you have ensure the followings −

  • Following example depends upon FileUpload, so ensure you have the most recent variant of commons-fileupload.x.x.jar file in your classpath. You can download it from

  • FileUpload depends upon Commons IO, so ensure you have the most recent variant of commons-io-x.x.jar file in your classpath. You can download it from

  • While testing following precedent, you attribute to upload a file which has less size than maxFileSize generally file would not be uploaded.

  • Make beyond any doubt you have made indexes c:\temp and c:\apache-tomcat8.0.28\webapps\data well ahead of time.

//Import required java libraries 


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; 


public class UploadServlet extends HttpServlet { 

private boolean isMultipart; 

private String filePath; 

private int maxFileSize = 50 * 1024; 

private int maxMemSize = 4 * 1024; 

private File file ;

public void init( ){ 

//Get the file area where it would be stored. 

filePath = getServletContext().getInitParameter("file-upload"); 


public void doPost(HttpServletRequest request, HttpServletResponse response) 

throws ServletException, { 

//Check that we have a file upload request 

isMultipart = ServletFileUpload.isMultipartContent(request); 

response.setContentType("text/html"); out = response.getWriter( ); 

if( !isMultipart ) { 



out.println("<title>Servlet upload</title>"); 



out.println("<p>No file uploaded</p>"); 





DiskFileItemFactory processing plant = new DiskFileItemFactory(); 

//greatest size that will be put away in memory 


//Location to spare information that is bigger than maxMemSize. 

factory.setRepository(new File("c:\\temp")); 

//Create another file upload handler 

ServletFileUpload upload = new ServletFileUpload(factory); 

//most extreme file size to be uploaded. 

upload.setSizeMax( maxFileSize );
   try { 

//Parse the demand to get file items. 

List fileItems = upload.parseRequest(request); 

//Process the uploaded file items 

Iterator I = fileItems.iterator(); 



out.println("<title>Servlet upload</title>"); 



while ( i.hasNext () ) { 

FileItem fi = (FileItem); 

if ( !fi.isFormField () ) { 

//Get the uploaded file parameters 

String fieldName = fi.getFieldName(); 

String fileName = fi.getName(); 

String contentType = fi.getContentType(); 

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: " + fileName + "<br>"); 





} catch(Exception ex) { 




public void doGet(HttpServletRequest request, HttpServletResponse response) 

throws ServletException, { 

throw new ServletException("GET method utilized with " + 

getClass( ).getName( )+": POST method required."); 




Compile and Running Servlet

Compile above servlet UploadServlet and make required passage in web.xml file as follows.










Now attempt to upload files utilizing the HTML form which you made above. When you would attempt http://localhost:8080/UploadFile.htm, it would show following outcome which would help you uploading any file from your local machine.


File Upload: 

Select a file to upload:

If your servlet text works fine, your file attribute to be uploaded in c:\apache-tomcat8.0.28\webapps\data\ directory.

© Javacodegeeks 2018 -
All Right Reserved and you agree to have read and accepted our term and condition.

Python 3