Servlet 3 File Upload Example using MultipartConfig shows you how to handle file upload with Servlet 3. This is additional feature that Servlet 3.0 Specification supports it out of the box. Thus, a annotation @MultiPartConfig has been introduced in Servlet 3.0 Specification. This annotation can be used to annotate a servlet class in order to handle request of type multipart and configure other upload file settings. Servlets that are annotated with MultipartConfig can retrieve the Part components by calling the request.getPart(String name) or request.getParts() method. This is thirteenth post of series of Java Servlet Tutorial. This series tutorial will provide you full knowledge about Servlet 3.0.
Table of contents:
1. Project structure
2. Maven dependency
3. @MultiPartConfig annotation introduction
4. Create File Upload Servlet
5. Create view
6. Deploy Servlet 3 File Upload Example using MultipartConfig
Project structure
We will create a project with structure like below
Maven dependency
We can use Servlet 3 API by adding the below dependency
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javabycode.servlet</groupId> <artifactId>MultipartConfig-Annotation-Example</artifactId> <version>1.0.0-SNAPSHOT</version> <name>MultipartConfig-Annotation-Example - ${project.artifactId}</name> <packaging>war</packaging> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>multipartconfig</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project> |
@MultiPartConfig annotation introduction
The @MultipartConfig annotation includes the following optional attributes:
location: An absolute path to a directory that ised to store files temporarily. This attribute does not support a path relative to the application context. The default location is “”.
fileSizeThreshold: If the upload file’s size is greater than this threshold, it will be stored temporarily in disk. Otherwise the file is stored in memory. Size in bytes and the default value is 0 bytes.
MaxFileSize: The maximum size of uploaded files, in bytes. If the size of any uploaded file is greater than this size, the exception (IllegalStateException) will be thrown. The default size is unlimited.
maxRequestSize: The maximum size of multipart/form-data request, in bytes. The exception will be thrown if the overall size of all uploaded files exceeds this threshold. The default size is unlimited.
Create File Upload Servlet
This following class shows how to configure a servlet to handle file upload using @MultipartConfig annotation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
package com.javabycode; 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; import java.io.IOException; import java.io.PrintWriter; import java.util.Collection; @WebServlet("/upload") @MultipartConfig(location = "C:/temp", fileSizeThreshold = 1024 * 1024 * 1, // 1 MB maxFileSize = 1024 * 1024 * 10, // 10 MB maxRequestSize = 1024 * 1024 * 15 // 15 MB ) public class UploadServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { getServletContext().getRequestDispatcher("/index.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); Collection<Part> parts = req.getParts(); out.write("<h2> Total files : "+parts.size()+"</h2>"); for(Part part : parts) { printPart(part, out); part.write(part.getSubmittedFileName()); } } private void printPart(Part part, PrintWriter pw) { StringBuffer sb = new StringBuffer(); sb.append("Name : "+part.getName()); sb.append("<br>"); sb.append("Content Type : "+part.getContentType()); sb.append("<br>"); sb.append("Size : "+part.getSize()); sb.append("<br>"); for(String header : part.getHeaderNames()) { sb.append(header + " : "+part.getHeader(header)); sb.append("<br>"); } pw.write(sb.toString()); } } |
Let’s dig deeper:
The getParts() method returns collections of all Part objects. If form has more than one input of type file, multiple Part objects are returned.
The javax.servlet.http.Part interface provide methods that allow to get information of each Part. The methods do the following: Retrieve the name, size, and content-type of the Part, Query the headers submitted with a Part, Delete a Part, Write a Part out to disk
Create view
For demonstration the above servlet, we create a view jsp like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<html> <head> </head> <body> <form action="upload" enctype="multipart/form-data" method="POST"> <table> <tr> <td colspan="2" style="padding:5">File Upload Form</td> </tr> <tr> <td style="padding:5">Select File</td> <td style="padding:5"><input type="file" name="fileUpload" /></td> </tr> <tr> <td colspan="2" style="padding:5"><input type="submit" value="Submit"/></td> </tr> </table> </form> </body> </html> |
Deploy Servlet 3 File Upload Example using MultipartConfig
Now, we are ready to build war file using maven and deploy it on servlet container (for example Tomcat 8). Then, running the address http://localhost:8080/multipartconfig/upload. A a upload form will appear and we browse a file such as the below screen shot:
Next, Click the submit button and we will get the uploaded file information like below:
That’s all on the tutorial Servlet 3 File Upload Example using MultipartConfig. You can also find other servlet example in the series of Java Servlet Example.
Download complete source code, please click link below
Servlet-3-MultipartConfig-Annotation-Example.zip (365 downloads)