Today we will look into Servlet 3 File Upload Example using @MultipartConfig annotation and javax.servlet.http.Part
. Sometime back I wrote an article about Servlet File Upload and I used Apache FileUpload API but here we will use Servlet 3 File Upload feature.
Since File Upload is a common task in web applications, Servlet Specs 3.0 provided additional support for uploading files to server and we don’t have to depend on any third party APIs for this. In this tutorial we will see how we can use Servlet 3.0 API for uploading Files to server.
We need to annotate File Upload handler servlet with MultipartConfig annotation to handle multipart/form-data requests that is used for uploading file to server. MultipartConfig annotation has following attributes:
Read more about annotations at Java Annotations Tutorial.
Part interface represents a part or form item that was received within a multipart/form-data POST request. Some important methods are getInputStream()
, write(String fileName)
that we can use to read and write file.
New methods got added in HttpServletRequest
to get all the parts in multipart/form-data request through getParts()
method. We can get a specific part using getPart(String partName)
method. Let’s see a simple project where we will use above API methods to upload file using servlet. Our project structure will look like below image.
We have a simple html page where we can select the file to upload and submit request to server to get it uploaded. index.html
<html>
<head></head>
<body>
<form action="FileUploadServlet" method="post" enctype="multipart/form-data">
Select File to Upload:<input type="file" name="fileName">
<br>
<input type="submit" value="Upload">
</form>
</body>
</html>
Here is our File Upload Servlet implementation. FileUploadServlet.java
package com.journaldev.servlet;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
@WebServlet("/FileUploadServlet")
@MultipartConfig(fileSizeThreshold=1024*1024*10, // 10 MB
maxFileSize=1024*1024*50, // 50 MB
maxRequestSize=1024*1024*100) // 100 MB
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 205242440643911308L;
/**
* Directory where uploaded files will be saved, its relative to
* the web application directory.
*/
private static final String UPLOAD_DIR = "uploads";
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// gets absolute path of the web application
String applicationPath = request.getServletContext().getRealPath("");
// constructs path of the directory to save uploaded file
String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR;
// creates the save directory if it does not exists
File fileSaveDir = new File(uploadFilePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdirs();
}
System.out.println("Upload File Directory="+fileSaveDir.getAbsolutePath());
String fileName = null;
//Get all the parts from request and write it to the file on server
for (Part part : request.getParts()) {
fileName = getFileName(part);
part.write(uploadFilePath + File.separator + fileName);
}
request.setAttribute("message", fileName + " File uploaded successfully!");
getServletContext().getRequestDispatcher("/response.jsp").forward(
request, response);
}
/**
* Utility method to get file name from HTTP header content-disposition
*/
private String getFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
System.out.println("content-disposition header= "+contentDisp);
String[] tokens = contentDisp.split(";");
for (String token : tokens) {
if (token.trim().startsWith("filename")) {
return token.substring(token.indexOf("=") + 2, token.length()-1);
}
}
return "";
}
}
Notice the use of @MultipartConfig annotation to specify different size parameters for upload file. We need to use request header “content-disposition” attribute to get the file name sent by client, we will save the file with same name. The directory location is relative to web application where I am saving the file, you can configure it to some other location like in Apache Commons FileUpload example.
A simple JSP page that will be sent as response to client once the file is uploaded successfully to server. response.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Upload File Response</title>
</head>
<body>
<%-- Using JSP EL to get message attribute value from request scope --%>
<h2>${requestScope.message}</h2>
</body>
</html>
There is nothing new in web.xml file for servlet file upload, it’s only used to make the index.html as welcome file. web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/javaee" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>ServletFileUploadExample</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Now when we run the application, we get following pages as response.
The logs will show the directory location where file is saved and content-disposition header information.
Upload File Directory=/Users/pankaj/Documents/workspace/j2ee/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/ServletFileUploadExample/uploads
content-disposition header= form-data; name="fileName"; filename="IMG_2046.jpg"
I am running Tomcat through Eclipse, that’s why file location is like this. If you run tomcat through command line and deploy application by exporting as WAR file into webapps directory, you will get different structure but a clear one.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
What if a user tries to access the Servlet directly? The @MultipartConfig fails what can be done in that case?
- Arun
I am getting Servlet.service() for servlet [com.journaldev.servlet.FileUploadServlet] in context with path [/Assign1] threw exception java.io.IOException: java.io.FileNotFoundException pls help me!!..
- suraj
Can you tell me the URL you are trying to access?
- Pankaj
https://localhost:8080/Assign1/
- suraj
Hello Pankaj, Thanks for tutorial. but i want to download the text file from server using same multipart or servlet 3.0, can use please provide me with the same?
- Sushank Dahiwadkar
one more thing ! plz share reply for this time on my mail id. cause for a very few moments i can access other sites at my workstation.plz.
- prashant
I think below for loop with take care of multiple files automatically. for (Part part : request.getParts()) { fileName = getFileName(part); part.write(uploadFilePath + File.separator + fileName); } I haven’t tested it though, please check.
- Pankaj
It’s ok, but if one of those file controls is empty, servlet crashes. I don’t know how fix it :(
- freyaa
Thanx 4 ur code it really helpful. Will u please tell me hoe to upload multiple files and store it into database and later download them
- Kedar
You can easily extend the program to store the files in Database using JDBC Connections.
- Pankaj
I want to integrate it in my project so what is the jar file I need to use. .
- Raghavendra M
Use servlet-api jar from Tomcat7, that implements Servlet-3 specs.
- Pankaj
What is the jar file I need to use .
- Raghavendra M
Now I want to display image on jsp which is stored on server . . . how to do that … can u send some code sample . .
- Raghavendra M
Hi I am using file upload along with other textfiled. My problem is, if I submit form as multipart/form-data all text fields will be null for getParameter() . So how to get the value of textfields when v send form as multipart/form-data.
- Raghavendra M
Thanks Buddy Your code help me and its work better.
- Ravi
Hi Pankaj, When I run this project using Glassfish 4.0 I end up with below error. It would be great if you could help to solve this. Thanks, Reginald HTTP Status 500 - Internal Server Error type Exception report messageInternal Server Error descriptionThe server encountered an internal error that prevented it from fulfilling this request. exception java.io.FileNotFoundException: C:\Users\Reginald\AppData\Roaming\NetBeans\7.4\config\GF_4.0\domain1\generated\jsp\FileUpl\C:\Users\Reginald\Documents\NetBeansProjects\FileUpl\build\web\uploads\C:\Users\Reginald\Documents\javaeetutorial6.pdf (The filename, directory name or volume label syntax is incorrect) note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 4.0 logs.
- Reginald Bal
For everyone who has problems with FileNotFoundException due to double path. Try adding “location” to @MultipartConfig, like this: @MultipartConfig(fileSizeThreshold=1024*1024*10, // 10 MB maxFileSize=1024*1024*50, // 50 MB maxRequestSize=1024*1024*100, // 100 MB location=“/” ) works for me.
- Andac
Sir m getting a painful error when m accessing the URL HTTP Status 404 - Not Found type Status report messageNot Found descriptionThe requested resource is not available. GlassFish Server Open Source Edition 4.0 URL is :
https://localhost:8080/WebApplication2/
I dont knw what to do wid it . M pestered- Aakanksha
when i click on the upload button it shows http status 404 error desrciption :requested resource is not available. apache tomcat /7.0.54 plz help me out …
- praveen
Hi, Thanks for the info, it really helped me a lot. Can you help me to retrieve these files from the database and display it using jap. Thanks in advance.
- Kiran G V
Hai Sir, There is problem in Content Disposition in IE the filename is takeing differently when compared to other browser please fine and provide solution.The Above code not work properly in IE.
- Manoj
This worked perfectly! Thank you so much for your work!!
- Bob
pankaj I am getting this error.please any one tell me how to solve it as soon as possible. SEVERE: Servlet.service() for servlet [FileUploadServlet] in context with path [/ems] threw exception java.io.IOException: java.io.FileNotFoundException: C:\apache-tomcat-7.0.56-windows-x64\apache-tomcat-7.0.56\wtpwebapps\ems\uploads\C:\Users\hello\Pictures\image002.jpg (The filename, directory name, or volume label syntax is incorrect) at org.apache.catalina.core.ApplicationPart.write(ApplicationPart.java:121) at FileUploadServlet.doPost(FileUploadServlet.java:44) at javax.servlet.http.HttpServlet.service(HttpServlet.java:646) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:662) Caused by: java.io.FileNotFoundException: C:\apache-tomcat-7.0.56-windows-x64\apache-tomcat-7.0.56\wtpwebapps\ems\uploads\C:\Users\hello\Pictures\image002.jpg (The filename, directory name, or volume label syntax is incorrect) at java.io.FileOutputStream.open(Native Method) at java.io.FileOutputStream.(FileOutputStream.java:179) at java.io.FileOutputStream.(FileOutputStream.java:131) at org.apache.tomcat.util.http.fileupload.disk.DiskFileItem.write(DiskFileItem.java:377) at org.apache.catalina.core.ApplicationPart.write(ApplicationPart.java:119) … 20 more
- Hariharanadh
I was uploaded video using this (request.getServletContext().getRealPath(“”);) path.Uploaded work.but how can i preview in jsp.${pagecontex.request.getRealPath(path)} wasn’t work.If any help for uploaded video need to play inside jsp using Video tag
- Madhawa
Thanks Pankaj,This example works fine…
- Deepak