Servlets - File Uploading

A Servlet can be utilized with a HTML structure tag to enable clients to transfer documents to the server. A transferred record could be a content record or picture document 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 structure method credit ought to be set to POST technique and GET strategy can not be used

  • The structure enctype ascribe ought to be set to multipart/structure data.

  • The structure action credit ought to be set to a servlet document which would deal with record transferring at backend server. Following model is utilizing UploadServlet servlet to transfer file.

  • To transfer a solitary record you should utilize a solitary <input .../> tag with property type="file". To permit various records transferring, incorporate more than one info labels with various qualities for the name characteristic. The program relates a Browse catch with each of them.




<title>File Uploading Form</title> 



<h3>File Upload:</h3> 

Select a document to transfer: <br /> 

<form action = "UploadServlet" method = "post" enctype = "multipart/structure 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 document from neighborhood PC and when client would click at "Transfer File", structure would be submitted alongside the chose fil −


File Upload: 

Select a document to transfer: 

NOTE: This is simply sham structure and would not work.

Writing Backend Servlet

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




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





</setting param> 



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

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

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

  • While testing following precedent, you ought to transfer a record which has less size than maxFileSize generally document 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 document ;

public void init( ){ 

//Get the document 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 record transfer request 

isMultipart = ServletFileUpload.isMultipartContent(request); 

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

if( !isMultipart ) { 



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



out.println("<p>No record 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 record transfer handler 

ServletFileUpload transfer = new ServletFileUpload(factory); 

//most extreme document size to be uploaded. 

upload.setSizeMax( maxFileSize );
   try { 

//Parse the demand to get record items. 

List fileItems = upload.parseRequest(request); 

//Process the transferred document items 

Iterator I = fileItems.iterator(); 



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



while ( i.hasNext () ) { 

FileItem fi = (FileItem); 

if ( !fi.isFormField () ) { 

//Get the transferred document 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 ) { 

document = new File( filePath + fileName.substring( fileName.lastIndexOf("\\"))) ; 

} else { 

document = new File( filePath + fileName.substring(fileName.lastIndexOf("\\")+1)) ; 


fi.write( record ) ; 

out.println("Uploaded Filename: " + fileName + "<br>"); 





} catch(Exception ex) { 




public void doGet(HttpServletRequest request, HttpServletResponse response) 

throws ServletException, { 

throw new ServletException("GET technique utilized with " + 

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




Compile and Running Servlet

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










Now attempt to transfer records utilizing the HTML structure which you made above. When you would attempt http://localhost:8080/UploadFile.htm, it would show following outcome which would help you transferring any document from your neighborhood machine.


File Upload: 

Select a document to upload:

If your servlet content works fine, your document ought to be transferred 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