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.

 

<html> 

<head> 

<title>File Uploading Form</title> 

</head> 

<body> 

<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" /> 

</form> 

</body> 

</html>

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 −

 

<web-app>
.... 

<context-param> 

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

<param-name>file-upload</param-name> 

<param-value> 

c:\apache-tomcat-5.5.29\webapps\data\ 

</param-value> 

</setting param> 

.... 

</web-app>

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 https://commons.apache.org/fileupload/.

  • 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 https://commons.apache.org/io/.

  • 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.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 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, java.io.IOException { 

//Check that we have a file upload request 

isMultipart = ServletFileUpload.isMultipartContent(request); 

response.setContentType("text/html"); 

java.io.PrintWriter out = response.getWriter( ); 

if( !isMultipart ) { 

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>"); 

return; 

} 

DiskFileItemFactory processing plant = new DiskFileItemFactory(); 

//greatest size that will be put away in memory 

factory.setSizeThreshold(maxMemSize); 

//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("<html>"); 

out.println("<head>"); 

out.println("<title>Servlet 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(); 

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>"); 

} 

} 

out.println("</body>"); 

out.println("</html>"); 

} catch(Exception ex) { 

System.out.println(ex); 

} 

} 

public void doGet(HttpServletRequest request, HttpServletResponse response) 

throws ServletException, java.io.IOException { 

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.

 

<servlet> 

<servlet-name>UploadServlet</servlet-name> 

<servlet-class>UploadServlet</servlet-class> 

</servlet> 

<servlet-mapping> 

<servlet-name>UploadServlet</servlet-name> 

<url-pattern>/UploadServlet</url-pattern> 

</servlet-mapping>

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