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:

 

Other Java Servlet Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment

   


Comments 

#1Aimilios2020-11-10 04:34
Great Work Nam, exceptional tutorials
Quote