--Control things like spring.servlet.multipart.max-file-size = 1MB on a URL-by-URL basis
--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);
	}
}
Please let me know if you can do it with Spring Boot settings. end.
Recommended Posts