[tomcat] How to set the max size of upload file

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?

This question is related to tomcat file-upload spring-boot jhipster

The answer is


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();
    }
}

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" />

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


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


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.


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.


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;

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/


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


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

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

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

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

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.


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

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


Examples related to tomcat

Jersey stopped working with InjectionManagerFactory not found The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat Spring boot: Unable to start embedded Tomcat servlet container Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists Spring Boot application in eclipse, the Tomcat connector configured to listen on port XXXX failed to start Kill tomcat service running on any port, Windows Tomcat 8 is not able to handle get request with '|' in query parameters? 8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE 403 Access Denied on Tomcat 8 Manager App without prompting for user/password Difference between Xms and Xmx and XX:MaxPermSize

Examples related to file-upload

bootstrap 4 file input doesn't show the file name How to post a file from a form with Axios File Upload In Angular? How to set the max size of upload file The request was rejected because no multipart boundary was found in springboot Send multipart/form-data files with angular using $http File upload from <input type="file"> How to upload files in asp.net core? REST API - file (ie images) processing - best practices Angular - POST uploaded file

Examples related to spring-boot

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Why am I getting Unknown error in line 1 of pom.xml? Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured How to resolve Unable to load authentication plugin 'caching_sha2_password' issue ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName ERROR Source option 1.5 is no longer supported. Use 1.6 or later How to start up spring-boot application via command line? JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

Examples related to jhipster

How to set the max size of upload file