I want to control the maximum file size in file upload for each URL in Spring Boot

1. What you want to do

--Control things like spring.servlet.multipart.max-file-size = 1MB on a URL-by-URL basis

2. Version, conditions, etc.

3. What I did

--Create the following Intercecptor and determine MultipartFile # size

MultipartFileInterceptor.java


public class MultipartFileInterceptor extends HandlerInterceptorAdapter {

	private final long maxFileSize;

	public MultipartFileInterceptor(long maxFileSize) {
		this.maxFileSize = maxFileSize;
	}
	
	public MultipartFileInterceptor(String maxFileSize) {
		this(ByteSizeUnit.toBytes(maxFileSize));
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
							 HttpServletResponse response,
							 Object handler) throws Exception {

		if (MultipartRequest.class.isInstance(request) && maxFileSize >= 0) {
			MultipartRequest multipartRequest = MultipartRequest.class.cast(request);

			multipartRequest.getFileMap()
				.values()
				.stream()
				.forEach(f -> {
					if (f.getSize() > maxFileSize) {
						throw new MaxUploadSizeExceededException(maxFileSize);
					}
				});
		}

		return super.preHandle(request, response, handler);
	}
}

--Create a WebMvcConfigurer like the one below and associate the Interceptor with the URL you want to control.

WebMvcConfig


@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

	@Value("${app.file.max-file-size:-1}")
	private String fileMaxFileSize;

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new MultipartFileInterceptor(fileMaxFileSize))
			.addPathPatterns("/file");
	}

}

--Although it is not directly related to this issue, by preparing the following class, it is possible to define it as 1MB in the application settings.

ByteSizeUnit.java


public enum ByteSizeUnit {

	KB {
		@Override
		long toBytes(long size) {
			return size * UNIT_SIZE;
		}
	},
	MB {
		@Override
		long toBytes(long size) {
			return size * UNIT_SIZE * UNIT_SIZE;
		}
	},
	GB {
		@Override
		long toBytes(long size) {
			return size * UNIT_SIZE * UNIT_SIZE * UNIT_SIZE;
		}
	};

	abstract long toBytes(long size);

	static final long UNIT_SIZE = 1024;

	public static long toBytes(String size) {
		if (Objects.isNull(size) || size.isEmpty()) {
			throw new IllegalArgumentException("size must not be empty");
		}

		for (ByteSizeUnit byteSizeUnit : values()) {
			if (size.toUpperCase().endsWith(byteSizeUnit.name())) {
				return byteSizeUnit.toBytes(Long.valueOf(size.substring(0, size.length() - byteSizeUnit.name().length())));
			}
		}

		return Long.valueOf(size);
	}

}
  1. Example

Please let me know if you can do it with Spring Boot settings. end.

Recommended Posts

I want to control the maximum file size in file upload for each URL in Spring Boot
I want to control the default error message of Spring Boot
What I did in the migration from Spring Boot 1.4 series to 2.0 series
What I did in the migration from Spring Boot 1.5 series to 2.0 series
[Spring Boot] I want to add my own property file and get the value with env.getProperty ().
I want to know the Method of the Controller where the Exception was thrown in the ExceptionHandler of Spring Boot
Procedure to make the value of the property file visible in Spring Boot
My memorandum that I want to make ValidationMessages.properties UTF8 in Spring Boot
How to bind to property file in Spring Boot
[Spring Boot] How to refer to the property file
I want to get the value in Ruby
How to set environment variables in the properties file of Spring boot application
I tried to implement file upload with Spring MVC
I tried to reduce the capacity of Spring Boot
How to test file upload screen in Spring + Selenium
Error handling when the maximum file size is exceeded when uploading a file with Spring Boot
I want to get the information of the class that inherits the UserDetails class of the user who is logged in with Spring Boot.
I want to read the property file with a file name other than application.yml or application- [profile name] .yml with Spring Boot.
[Ruby on Rails] I want to get the URL of the image saved in Active Storage
Change the injection target for each environment with Spring Boot 2
I want to set the conditions to be displayed in collection_check_boxes
I want to control the display of the upper management navigation bar (Control menu) in Liferay 7 / DXP
[Rails] [bootstrap] I want to change the font size responsively
File upload with Spring Boot
I want to get a list of the contents of a zip file and its uncompressed size
I want to change the color of the upper control navigation bar (Control menu) in Liferay 7 / DXP
I want to create a Parquet file even in Ruby
I want to transition to the same screen in the saved state
I want to return multiple return values for the input argument
How to control transactions in Spring Boot without using @Transactional
I want to simplify the conditional if-else statement in Java
I want to create a chat screen for the Swift chat app!
I want to understand the flow of Spring processing request parameters
The story of Collectors.groupingBy that I want to keep for posterity
[Eclipse] I want to open the same file twice [Split editor]
I want to display the images under assets/images in the production environment
I want to remove the top margin in Grouped UITableView (swift)
[Java] I want to perform distinct with the key in the object
I want to change the value of Attribute in Selenium of Ruby
[Android] I want to get the listener from the button in ListView
Spring Boot for the first time
[For beginners] I want to automatically enter pre-registered data in the input form with a selection command.
[Spring Boot] List of validation rules that can be used in the property file for error messages
[Ruby] I want to output only the odd-numbered characters in the character string
Spring.messages.fallback-to-system-locale: false is required to default message.properties for i18n support in Spring boot
I want to write JSP in Emacs more easily than the default.
[Spring Boot] I investigated how to implement post-processing of the received request.
I want to display the number of orders for today using datetime.
Glassfish tuning list that I want to keep for the time being
I got stuck using snake case for variable name in Spring Boot
Workaround for Command Line Runner to work with JUnit in Spring Boot
I used Docker to solidify the template to be developed with spring boot.
I want to get the IP address when connecting to Wi-Fi in Java
I want to display an error message when registering in the database
[For internal use] For those assigned to the Spring Boot project (under construction)
[Java Spring MVC] I want to use DI in my own class
"Teacher, I want to implement a login function in Spring" ① Hello World
I want you to use Enum # name () for the Key of SharedPreference
Static file access priority in Spring boot
Local file download memorandum in Spring Boot
I want to use @Autowired in Servlet