How to restrict users from uploading huge files in Spring Boot?

Let’s say you have created a REST API which accepts files as input.

You deployed the API and users started uploading huge files and your server’s memory gets fast filled up.

How do you prevent this?

You can do this with zero code changes in Spring Boot.

All you have to do is add a property in your file.

Here is a sample API which accepts a multipart file:

	public String upload(@RequestPart("file") MultipartFile file) {

		return file.getOriginalFilename();

Let’s upload a file of size 270+ KB:

Now let’s say you want to restrict the user not to upload a file of size greater than 150KB.

You just need to add the below property in application.yml:

      max-file-size: 150KB

Now if I fire the same request it throws error:

Here is the error from the console:

org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 153600 bytes.
	at org.apache.tomcat.util.http.fileupload.impl.FileItemStreamImpl$1.raiseError( ~[tomcat-embed-core-9.0.56.jar:9.0.56]
	at org.apache.tomcat.util.http.fileupload.util.LimitedInputStream.checkLimit( ~[tomcat-embed-core-9.0.56.jar:9.0.56]
	at ~[tomcat-embed-core-9.0.56.jar:9.0.56]
	at java.base/ ~[na:na]

Now , what if your API accepts multiple files.

This restriction works only at a single file level.

What if you want to restrict the total size of your entire request?

Consider this example API:

	public String upload(@RequestPart("file1") MultipartFile file1,@RequestPart("file2") MultipartFile file2) {

		return file1.getOriginalFilename()+","+file2.getOriginalFilename();

It accepts two files.

If you upload each file of size less than 150 KB it works fine:

But if you don’t want the total size to exceed 150 KB you can use one more property:

      max-request-size: 150KB

Now if I hit the same API , it throws error:

A different error in the console:

org.apache.tomcat.util.http.fileupload.impl.SizeLimitExceededException: the request was rejected because its size (297072) exceeds the configured maximum (153600)
	at org.apache.tomcat.util.http.fileupload.impl.FileItemIteratorImpl.init( ~[tomcat-embed-core-9.0.56.jar:9.0.56]
	at org.apache.tomcat.util.http.fileupload.impl.FileItemIteratorImpl.getMultiPartStream( ~[tomcat-embed-core-9.0.56.jar:9.0.56]
	at org.apache.tomcat.util.http.fileupload.impl.FileItemIteratorImpl.findNextItem( ~[tomcat-embed-core-9.0.56.jar:9.0.56]
	at org.apache.tomcat.util.http.fileupload.impl.FileItemIteratorImpl.<init>( ~[tomcat-embed-core-9.0.56.jar:9.0.56]

That’s it!





Leave a Reply

%d bloggers like this: