How to set the max size of upload file

TomcatFile UploadSpring BootJhipster

Tomcat Problem Overview


I'm developing application based on Spring Boot and AngularJS using JHipster. My question is how to set max size of uploading files?

If I'm trying to upload to big file I'm getting this information in console:

  DEBUG 11768 --- [io-8080-exec-10] c.a.app.aop.logging.LoggingAspect: 

Enter: com.anuglarspring.app.web.rest.errors.ExceptionTranslator.processRuntimeException() with argument[s] = 

[org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.lang.IllegalStateException: 

org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 1048576 bytes.]

And server response with status 500.

How to set that?

Tomcat Solutions


Solution 1 - Tomcat

Also in Spring boot 1.4, you can add following lines to your application.properties to set the file size limit:

spring.http.multipart.max-file-size=128KB
spring.http.multipart.max-request-size=128KB

for spring boot 2.x and above its

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

Worked for me. Source: https://spring.io/guides/gs/uploading-files/

UPDATE:

Somebody asked the differences between the two properties.

Below are the formal definitions:

> MaxFileSize: The maximum size allowed for uploaded files, in bytes. If the size of any uploaded file is greater than this size, the web container will throw an exception (IllegalStateException). The default size is unlimited. > > MaxRequestSize: The maximum size allowed for a multipart/form-data request, in bytes. The web container will throw an exception if the overall size of all uploaded files exceeds this threshold. The default size is unlimited.

To explain each:

MaxFileSize: The limit for a single file to upload. This is applied for the single file limit only.

MaxRequestSize: The limit for the total size of all files in a single upload request. This checks the total limit. Let's say you have two files a.txt and b.txt for a single upload request. a.txt is 5kb and b.txt is 7kb so the MaxRequestSize should be above 12kb.

Solution 2 - Tomcat

In Spring Boot 2 the spring.http.multipart changed to spring.servlet.multipart

https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0.0-M1-Release-Notes#multipart-configuration

Solution 3 - Tomcat

For Spring Boot 2.+, make sure you are using spring.servlet instead of spring.http.

---
spring:
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 10MB

If you have to use tomcat, you might end up creating EmbeddedServletContainerCustomizer, which is not really nice thing to do.

If you can live without tomat, you could replace tomcat with e.g. undertow and avoid this issue at all.

Solution 4 - Tomcat

You need to set the multipart.maxFileSize and multipart.maxRequestSize parameters to higher values than the default. This can be done in your spring boot configuration yml files. For example, adding the following to application.yml will allow users to upload 10Mb files:

multipart:
    maxFileSize: 10Mb
    maxRequestSize: 10Mb

If the user needs to be able to upload multiple files in a single request and they may total more than 10Mb, then you will need to configure multipart.maxRequestSize to a higher value:

multipart:
    maxFileSize: 10Mb
    maxRequestSize: 100Mb

Source: https://spring.io/guides/gs/uploading-files/

Solution 5 - Tomcat

There is some difference when we define the properties in the application.properties and application yaml.

In application.yml :

spring:
    http:
      multipart:
       max-file-size: 256KB
       max-request-size: 256KB

And in application.propeties :

spring.http.multipart.max-file-size=128KB
spring.http.multipart.max-request-size=128KB

Note : Spring version 4.3 and Spring boot 1.4

Solution 6 - Tomcat

In spring 2.x . Options have changed slightly. So the above answers are almost correct but not entirely . In your application.properties file , add the following-

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

Solution 7 - Tomcat

More specifically, in your application.yml configuration file, add the following to the "spring:" section.

http:
    multipart:
        max-file-size: 512MB
        max-request-size: 512MB

Whitespace is important and you cannot use tabs for indentation.

Solution 8 - Tomcat

I found the the solution at Expert Exchange, which worked fine for me.

@Bean
public MultipartConfigElement multipartConfigElement() {
    MultipartConfigFactory factory = new MultipartConfigFactory();
    factory.setMaxFileSize("124MB");
    factory.setMaxRequestSize("124MB");
    return factory.createMultipartConfig();
}

Ref: https://www.experts-exchange.com/questions/28990849/How-to-increase-Spring-boot-Tomcat-max-file-upload-size.html

Solution 9 - Tomcat

These properties in spring boot application.properties makes the acceptable file size unlimited -

# To prevent maximum upload size limit exception
spring.servlet.multipart.max-file-size=-1
spring.servlet.multipart.max-request-size=-1

Solution 10 - Tomcat

I'm using spring-boot-1.3.5.RELEASE and I had the same issue. None of above solutions are not worked for me. But finally adding following property to application.properties was fixed the problem.

multipart.max-file-size=10MB

Solution 11 - Tomcat

If you get a "connection resets" error, the problem could be in the Tomcat default connector maxSwallowSize attribute added from Tomcat 7.0.55 (ChangeLog)

From Apache Tomcat 8 Configuration Reference

> maxSwallowSize: > The maximum number of request body bytes (excluding transfer encoding > overhead) that will be swallowed by Tomcat for an aborted upload. An > aborted upload is when Tomcat knows that the request body is going to > be ignored but the client still sends it. If Tomcat does not swallow > the body the client is unlikely to see the response. If not specified > the default of 2097152 (2 megabytes) will be used. A value of less > than zero indicates that no limit should be enforced.

For Springboot embedded Tomcat declare a TomcatEmbeddedServletContainerFactory

Java 8:

@Bean
public TomcatEmbeddedServletContainerFactory tomcatEmbedded() {
    TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
    tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
        if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
            //-1 for unlimited
            ((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
        }
    });
    return tomcat;
}

Java 7:

@Bean
public TomcatEmbeddedServletContainerFactory tomcatEmbedded() {
    TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
    tomcat.addConnectorCustomizers(new TomcatConnectorCustomizer()  {
		@Override
		public void customize(Connector connector) {
            if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
                //-1 for unlimited
                ((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
            }
		}
    });
    return tomcat;
}

Or in the Tomcat/conf/server.xml for 5MB

<Connector port="8080" protocol="HTTP/1.1"
       connectionTimeout="20000"
       redirectPort="8443"
       maxSwallowSize="5242880" />

Solution 12 - Tomcat

I know this is extremely late to the game, but I wanted to post the additional issue I faced when using mysql, if anyone faces the same issue in future.

As some of the answers mentioned above, setting these in the application.properties will mostly fix the problem

spring.http.multipart.max-file-size=16MB
spring.http.multipart.max-request-size=16MB

I am setting it to 16 MB, because I am using mysql MEDIUMBLOB datatype to store the file.

But after fixing the application.properties, When uploading a file > 4MB gave the error: org.springframework.dao.TransientDataAccessResourceException: PreparedStatementCallback; SQL [insert into test_doc(doc_id, duration_of_doc, doc_version_id, file_name, doc) values (?, ?, ?, ?, ?)]; Packet for query is too large (6656781 > 4194304). You can change this value on the server by setting the max_allowed_packet' variable.; nested exception is com.mysql.jdbc.PacketTooBigException: Packet for query is too large (6656781 > 4194304). You can change this value on the server by setting the max_allowed_packet' variable.

So I ran this command from mysql:

SET GLOBAL max_allowed_packet = 1024*1024*16;

Solution 13 - Tomcat

Aligned with the answer of Askerali Maruthullathil, this is what is working for me (Spring boot with Spring 5.2.2):

@Configuration
public class MultipartRequestFileConfig {

    @Bean(name = "multipartResolver")
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
        resolver.setDefaultEncoding("UTF-8");
        resolver.setResolveLazily(true);
        resolver.setMaxInMemorySize(83886080);
        resolver.setMaxUploadSize(83886080);
        return resolver;
    }
}

Solution 14 - Tomcat

To avoid this exception you can take help of VM arguments just as I used in Spring 1.5.8.RELEASE:

-Dspring.http.multipart.maxFileSize=70Mb
-Dspring.http.multipart.maxRequestSize=70Mb

Solution 15 - Tomcat

None of the configuration above worked for me with a Spring application.

Implementing this code in the main application class (the one annotated with @SpringBootApplication) did the trick.

@Bean 
EmbeddedServletContainerCustomizer containerCustomizer() throws Exception {
	 return (ConfigurableEmbeddedServletContainer container) -> {
	 
	          if (container instanceof TomcatEmbeddedServletContainerFactory) {
	 
	              TomcatEmbeddedServletContainerFactory tomcat = (TomcatEmbeddedServletContainerFactory) container;
	              tomcat.addConnectorCustomizers(
	                      (connector) -> {
	                    	  connector.setMaxPostSize(10000000);//10MB
	                      }
	              );
	          }
    };
}

You can change the accepted size in the statement: > connector.setMaxPostSize(10000000);//10MB

Solution 16 - Tomcat

For me nothing of previous works (maybe use application with yaml is an issue here), but get ride of that issue using that:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.util.unit.DataSize;

import javax.servlet.MultipartConfigElement;

@ServletComponentScan
@SpringBootApplication
public class App {
	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}

	@Bean
	MultipartConfigElement multipartConfigElement() {
	    MultipartConfigFactory factory = new MultipartConfigFactory();
	    factory.setMaxFileSize(DataSize.ofBytes(512000000L));
	    factory.setMaxRequestSize(DataSize.ofBytes(512000000L));
	    return factory.createMultipartConfig();
	}
}

Solution 17 - Tomcat

I had used this configuration with spring-boot 2.5.2 and it works fine:

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

Look at the official documentation: https://spring.io/guides/gs/uploading-files/

Solution 18 - Tomcat

If you request flow through the Netflix Zuul edge service, make sure to update the below properties in both Zuul and your file upload service.

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

Solution 19 - Tomcat

put this in your application.yml file to allow uploads of files up to 900 MB

server:
  servlet:
    multipart:
      enabled: true
      max-file-size: 900000000  #900M
      max-request-size: 900000000

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichał StyśView Question on Stackoverflow
Solution 1 - TomcatBahadir TasdemirView Answer on Stackoverflow
Solution 2 - TomcatAllar SaarnakView Answer on Stackoverflow
Solution 3 - TomcatOndrej KvasnovskyView Answer on Stackoverflow
Solution 4 - TomcatgeraldhumphriesView Answer on Stackoverflow
Solution 5 - TomcatdenzalView Answer on Stackoverflow
Solution 6 - TomcatsapyView Answer on Stackoverflow
Solution 7 - TomcatMobileMateoView Answer on Stackoverflow
Solution 8 - TomcatAskerali MaruthullathilView Answer on Stackoverflow
Solution 9 - TomcatthedevdView Answer on Stackoverflow
Solution 10 - TomcatChathura BuddhikaView Answer on Stackoverflow
Solution 11 - TomcatAlmalerikView Answer on Stackoverflow
Solution 12 - Tomcatshe12View Answer on Stackoverflow
Solution 13 - TomcatEnrique Jimenez FloresView Answer on Stackoverflow
Solution 14 - TomcatKhushboo SharmaView Answer on Stackoverflow
Solution 15 - TomcatTomer ShayView Answer on Stackoverflow
Solution 16 - Tomcatuser11999314View Answer on Stackoverflow
Solution 17 - TomcatIDIRView Answer on Stackoverflow
Solution 18 - TomcatDenuwan.hhView Answer on Stackoverflow
Solution 19 - TomcatGankView Answer on Stackoverflow