Apache FileUpload, Java

How to upload a file using servlet in Java?

This post illustrates how we can upload a file using Apache Commons FileUpload API in Java. In order to use the FileUpload API, you need to include commons-fileupload.jar file to your class path. The commons-fileupload.jar has a dependency on commons-io.jar. So, make sure you download and add both the JAR files to your project’s class path.

If using Maven build tool, you need to add both the dependencies in the project’s pom.xml file.

		<!-- File Upload Dependency -->
		<dependency>
        	<groupId>commons-fileupload</groupId>
        	<artifactId>commons-fileupload</artifactId>
        	<version>1.2.2</version>
		</dependency>
		
		<!-- Commons IO Dependency -->
		<dependency>
    		<groupId>commons-io</groupId>
    		<artifactId>commons-io</artifactId>
    		<version>2.2</version>
		</dependency>

The next step is to create a HTML file upload form. It should look like this:

<form action="uploadservlet" enctype="multipart/form-data" method="post">;
      <input name="file" type="file" />;
      <input name="submit" type="submit" value="Submit" />;
</form>

Next, we need to include the mapping of uploadservlet to our UploadServlet.

	<servlet>
		<servlet-name>uploadservlet</servlet-name>
		<servlet-class>com.devesh.UploadProject.UploadServlet</servlet-class>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>uploadservlet</servlet-name>
		<url-pattern>uploadservlet</url-pattern>
	</servlet-mapping>

The doPost() method in UploadServlet will look like this:

	public void doPost(
			HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, IOException {
		
		try {
			FileItemFactory itemFactory = new DiskFileItemFactory();
			ServletFileUpload fileUpload = new ServletFileUpload(itemFactory);
			List<FileItem> fileItems = fileUpload.parseRequest(request);
			
			for (FileItem fileItem : fileItems) {
				
	            if (fileItem.isFormField()) {
	            	
	            	// Regular form fields like Submit button, etc
	                String fieldName = fileItem.getFieldName();
	                String fieldValue = fileItem.getString();
	            } else {
	            	
	                // File Item
	                String fieldName = fileItem.getFieldName();
	                String fileName = fileItem.getName();
	                String contentType = fileItem.getContentType();
	                
	                // Here you can get the file item as InputStream 
	                // and do further processing on the file. 
	                InputStream inputStream = fileItem.getInputStream();
	            }
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
	}

That’s it! The user of the Apache Commons FileUpload API makes it super easy to upload a file using servlet/jsp in Java.

Advertisements