Java Servlet @MultipartConfig Annotation Example
- Details
- Written by Nam Ha Minh
- Last Updated on 26 June 2019   |   Print Email
The @MultipartConfigannotation is used to annotate a servlet class in order to handle multipart/form-data requests and configure various upload settings. When a servlet is annotated by this annotation, we can access all parts via the methods getParts() and an individual part via the method getPart(name) of the HttpServletRequest object, and write the upload file to disk via the method write(fileName) of the Part object.
Use this annotation if you want to handle file upload through servlet (See the tutorial: How to write upload file servlet with Servlet 3.0 API).
Syntax of @MultipartConfig Annotation:
@MultipartConfig( fileSizeThreshold = <size in bytes>, maxFileSize = <size in bytes>, maxRequestSize = <size in bytes>, location = <save location> )
Attributes of @MultipartConfig Annotation:
Name | Type | Required | Description |
fileSizeThreshold | int | Optional | Specify size threshold when saving the upload file temporarily. If the upload file’s size is greater than this threshold, it will be stored in disk. Otherwise the file is stored in memory. Size in bytes. |
location | String | Optional | Specify directory where upload files are stored |
maxFileSize | long | Optional | Specify maximum size of an upload file. Size in bytes. |
maxRequestSize | long | Optional | Specify maximum size of a request (including both upload files and other form data). Size in bytes. |
Examples of @MultipartConfig Annotation:
The following example illustrates how to configure a servlet to handle file upload using @MultipartConfigannotation:
import java.io.IOException; 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; @WebServlet("/uploadFiles") @MultipartConfig( fileSizeThreshold = 1024 * 1024 * 1, // 1 MB maxFileSize = 1024 * 1024 * 10, // 10 MB maxRequestSize = 1024 * 1024 * 15, // 15 MB location = "D:/Uploads" ) public class FileUploadServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { // handles file upload... } }
Related Java Servlet Annotations:
- @WebServlet annotation
- @WebFilter annotation
- @WebListener annotation
- @WebInitParam annotation
- @HandlesTypes annotation
- @ServletSecurity, @HttpMethodContraint and @HttpConstraint annotations
Other Java Servlet Tutorials:
- Java Servlet Quick Start for beginners (XML)
- Java Servlet for beginners (annotations)
- Java Servlet and JSP Hello World Tutorial with Eclipse, Maven and Apache Tomcat
- Handling HTML form data with Java Servlet
- Java File Download Servlet Example
Comments