Increase HTTP Post maxPostSize in Spring Boot
Asked Answered
C

17

77

I've got a fairly simple Spring Boot web application, I have a single HTML page with a form with enctype="multipart/form-data". I'm getting this error:

The multi-part request contained parameter data (excluding uploaded files) that exceeded the limit for maxPostSize set on the associated connector.

I'm using Spring Boot's default embedded tomcat server. Apparently the default maxPostSize value is 2 megabytes. Is there any way to edit this value? Doing so via application.properties would be best, rather than having to create customized beans or mess with xml files.

Cogswell answered 20/10, 2015 at 9:26 Comment(3)
Whereever you have declared your multi-part resolver, you can change these things.Craver
I haven't declared it anywhere. I'm assuming that means spring boot is automatically creating and handling it. Does that mean I can't edit it?Cogswell
You can edit it. Find the multipart resolver and edit the value. If there is multipart support, I am sure you will find some configuration for it. You have not even posted your config in the main post, so no one can even point out what to change.Craver
C
21

Found a solution. Add this code to the same class running SpringApplication.run.

// Set maxPostSize of embedded tomcat server to 10 megabytes (default is 2 MB, not large enough to support file uploads > 1.5 MB)
@Bean
EmbeddedServletContainerCustomizer containerCustomizer() throws Exception {
    return (ConfigurableEmbeddedServletContainer container) -> {
        if (container instanceof TomcatEmbeddedServletContainerFactory) {
            TomcatEmbeddedServletContainerFactory tomcat = (TomcatEmbeddedServletContainerFactory) container;
            tomcat.addConnectorCustomizers(
                (connector) -> {
                    connector.setMaxPostSize(10000000); // 10 MB
                }
            );
        }
    };
}

Edit: Apparently adding this to your application.properties file will also increase the maxPostSize, but I haven't tried it myself so I can't confirm.

multipart.maxFileSize=10Mb # Max file size.
multipart.maxRequestSize=10Mb # Max request size.
Cogswell answered 16/11, 2015 at 0:37 Comment(4)
adding the properties works for me: multipart.maxFileSize and multipart.maxRequestSizeBossism
the connector solution didn't work for me, neither did the multipart.maxFileSize. What worked for me was spring.http.multipart.max-file-size from the answer below.Arly
This solution is perfect if you need to POST (ou PUT) a payload request (not file upload) with more tem 2 MB. It's working fine to post a request with 9 MB (some form fields with some Base64 encoded files as string).Nobell
Currently, you can not import the class EmbeddedServletContainerCustomizer, does it have any alternative?Deviltry
A
80

In application.properties file write this:

# Max file size.
spring.http.multipart.max-file-size=1Mb
# Max request size.
spring.http.multipart.max-request-size=10Mb

Adjust size according to your need.


Update

Note: As of Spring Boot 2, however you can now do

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

Appendix A. Common application properties - Spring

Aircrewman answered 20/10, 2015 at 9:36 Comment(8)
Tried that, still gave me errors. I'm not actually uploading any files in the form, I just have a lot of input fields with values tens of thousands of characters long, and if I have too much text (more than 2MB of text) it crashes. Was hoping to increase the postMaxSize to more than 2MB to avoid this problem.Cogswell
The dashes should not be included in the property names. multipart.maxRequestSize=20MB multipart.maxFileSize=20MBSabra
spring.http.multipart.max-file-size=1Mb # Max file size. Values can use the suffixed "MB" or "KB" to indicate a Megabyte or Kilobyte size. spring.http.multipart.max-request-size=10Mb # Max request size. Values can use the suffixed "MB" or "KB" to indicate a Megabyte or Kilobyte size.Underpinning
Deprecated now :( EDIT: Nevermind, found a soluting - editing this post.Consuelaconsuelo
@ImpulseTheFox Thanks for the update. I've updated the answer. :)Aircrewman
For me at spring version 2.0.0.RELEASE the old (and depricated) properties DID NOT WORK AT ALL. so you MUST use the new ones.Sulky
@Sabra Spring Boot does support the lower hyphen case as well, which is more readable.Kreitman
This doesn't seem to work on 2.5.0. Spring itself doesn't complain anymore, but the Tomcat connector still throws the error.Agone
S
25

If you are using using x-www-form-urlencoded mediatype in your POST requests (as I do), the multipart property of spring-boot does not work. If your spring-boot application is also starting a tomcat, you need to set the following property in your application.properties file:

# Setting max size of post requests to 6MB (default: 2MB)
server.tomcat.max-http-post-size=6291456

I could not find that information anywhere in the spring-boot documentations. Hope it helps anybody who also sticks with x-www-form-urlencoded encoding of the body.

Slave answered 21/8, 2018 at 13:53 Comment(3)
Looks like it is also true for multipart requests. I use Spring Boot 2.0.4.RELEASE with Tomcat Embed 8.5.32.I have the same error message as in question, the exception is thrown in org.apache.catalina.connector.Request because the following check succeeds: "if (postSize > maxPostSize) { ... ". And this internal maxPostSize field can only be altered with "server.tomcat.max-http-post-size" property.Simasimah
@StanislavMamontov I use Spring Boot 2.0.3.RELEASE and for me the "spring.servlet.multipart" property worked for multipart, but for x-www-form-urlencoded I had to use the "server.tomcat.max-http-post-size" property.Slave
Thanks for the hint - the property is listed here docs.spring.io/spring-boot/docs/current/reference/html/… as well and is called server.tomcat.max-http-form-post-size nowMarna
C
21

Found a solution. Add this code to the same class running SpringApplication.run.

// Set maxPostSize of embedded tomcat server to 10 megabytes (default is 2 MB, not large enough to support file uploads > 1.5 MB)
@Bean
EmbeddedServletContainerCustomizer containerCustomizer() throws Exception {
    return (ConfigurableEmbeddedServletContainer container) -> {
        if (container instanceof TomcatEmbeddedServletContainerFactory) {
            TomcatEmbeddedServletContainerFactory tomcat = (TomcatEmbeddedServletContainerFactory) container;
            tomcat.addConnectorCustomizers(
                (connector) -> {
                    connector.setMaxPostSize(10000000); // 10 MB
                }
            );
        }
    };
}

Edit: Apparently adding this to your application.properties file will also increase the maxPostSize, but I haven't tried it myself so I can't confirm.

multipart.maxFileSize=10Mb # Max file size.
multipart.maxRequestSize=10Mb # Max request size.
Cogswell answered 16/11, 2015 at 0:37 Comment(4)
adding the properties works for me: multipart.maxFileSize and multipart.maxRequestSizeBossism
the connector solution didn't work for me, neither did the multipart.maxFileSize. What worked for me was spring.http.multipart.max-file-size from the answer below.Arly
This solution is perfect if you need to POST (ou PUT) a payload request (not file upload) with more tem 2 MB. It's working fine to post a request with 9 MB (some form fields with some Base64 encoded files as string).Nobell
Currently, you can not import the class EmbeddedServletContainerCustomizer, does it have any alternative?Deviltry
S
19

Apply settings for Tomcat as well as servlet

You can set the max post size for Tomcat in application.properties which is set with an int as below. Just setting spring.servlet.multipart.max-request-size=10MB, as in some other answers, may not be enough.

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

# Server properties
server.tomcat.max-http-post-size=100000000
server.tomcat.max-swallow-size=100000000

Working with Spring Boot 2.0.5.RELEASE

Shuping answered 23/8, 2019 at 20:39 Comment(2)
[NOTE] Since Spring Boot version 2.1.x the Tomcat related property name is changed (added the word "form") and is now the following: server.tomcat.max-http-form-post-size. This can be already seen in the Spring Boot's official list of Common Application properties.Fowler
We can use readable format for below as well. # Server properties server.tomcat.max-http-post-size=10MB server.tomcat.max-swallow-size=10MBValoniah
D
8

First, 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.

Discourtesy answered 24/1, 2018 at 17:6 Comment(1)
Undertow has the same issue so switching does not avoid this problem. The config in this answer works with Undertow in the latest versions of Spring-Boot v1.5.9Cailly
P
7

Spring-boot 2.2.x has changed

server.tomcat.max-http-post-size 

to

server.tomcat.max-http-form-post-size

spring-boot-issue

Parturifacient answered 23/6, 2021 at 12:51 Comment(1)
Could you add a link to the docs, this would be awesomeAlacrity
S
6

The error here is not caused by max-file-size or max-request-size (as pointed out) but rather the container-specific max-http-post-size property. For tomcat (the default container), you can set:

server.tomcat.max-http-post-size: 10MB

Jetty:

server.jetty.max-http-post-size: 10MB

Undertow:

server.undertow.max-http-post-size: 10MB

This has the same effect as OP's answer here, but via application.properties which is much more preferable.

Squinch answered 20/5, 2020 at 6:24 Comment(0)
K
5

None of the solutions did work for me and most of them are just downright offtopic because OP is talking about maxPostSize, and not maxFileSize (latter gives you a different error anyway if the size is exceeded)

Solution: in /tomcat/conf/server.xml add maxPostSize="" attribute to Connector

<!-- A "Connector" represents an endpoint by which requests are received
     and responses are returned. Documentation at :
     Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
     Java AJP  Connector: /docs/config/ajp.html
     APR (HTTP/AJP) Connector: /docs/apr.html
     Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
-->
<Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           maxPostSize="10485760"
           redirectPort="8443" />
Kwarteng answered 20/2, 2019 at 14:25 Comment(0)
G
5

I was facing kind a similar issue. Where the Error I recieved is -

 "IllegalStateException multi-part request contained parameter data (excluding uploaded files) that exceeded the limit for maxPostSize set on the associated connector"

Solution I have applied following property, Where using max-http-form-post-size property did actually worked for me -

server:
  tomcat:
    max-http-form-post-size: 100000000
    max-swallow-size: 100000000

Along with -

spring:
  servlet:
    multipart:
      maxFileSize: 10MB
      maxRequestSize: 10MB

Above configuration worked properly.

Gratulate answered 19/10, 2020 at 16:24 Comment(2)
This really looks like an real answer who faced issue before. thanks @LokiMerchandising
GRADLE: server.tomcat.max-http-form-post-size=10000000 server.tomcat.max-swallow-size=10000000Chalky
M
4

from documentation: https://spring.io/guides/gs/uploading-files/

Tuning file upload limits

When configuring file uploads, it is often useful to set limits on the size of files. Imagine trying to handle a 5GB file upload! With Spring Boot, we can tune its auto-configured MultipartConfigElement with some property settings.

Add the following properties to your existing src/main/resources/application.properties:

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

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

The multipart settings are constrained as follows:

  • spring.http.multipart.max-file-size is set to 128KB, meaning total file size cannot exceed 128KB.

  • spring.http.multipart.max-request-size is set to 128KB, meaning total request size for a multipart/form-data cannot exceed 128KB.

Margarettemargarida answered 4/1, 2017 at 15:43 Comment(0)
S
4

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();
    }
}
Sielen answered 30/8, 2019 at 12:14 Comment(0)
A
3

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

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

Antislavery answered 17/1, 2017 at 11:56 Comment(0)
G
2

In Spring Boot >2 version, you can simply add following to the "application.properties" file:

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=20MB
Giuditta answered 1/7, 2020 at 23:49 Comment(0)
H
2

I have tried every property and solution mentioned here. Nothing works with SpringBoot 2.7.0 for me when running ./gradlew bootRun.

What I ended up doing was adding a custom filter.

public class Application
{
   private static final int DEFAULT_LIMIT = 10 * 1024 * 1024;

   public static void main(String[] args)
   {
      SpringApplication.run(Application.class, args);
   }

   @Bean
   public FilterRegistrationBean<RequestBodyLimitFilter> createRequestBodyLimitFilter(
         @Value("${PAYLOAD_LIMIT:" + DEFAULT_LIMIT + "}") Integer limitBytes)
   {
      FilterRegistrationBean<RequestBodyLimitFilter> registration = new FilterRegistrationBean<>();
      registration.setFilter(new RequestBodyLimitFilter(limitBytes));
      registration.setName("RequestBodyLimitFilter");
      return registration;
   }
}

And RequestBodyLimitFilter:

public class RequestBodyLimitFilter implements Filter
{
   private static Logger LOG = Logger.getLogger(RequestBodyLimitFilter.class.getName());
   private final Integer limitBytes;

   public RequestBodyLimitFilter(Integer limitBytes)
   {
      this.limitBytes = limitBytes;
   }

   @Override
   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
   {
      long contentLengthLong = request.getContentLengthLong();
      if (contentLengthLong > limitBytes)
      {
         LOG.info("Received " + contentLengthLong + " limit is " + limitBytes);
         HttpServletResponse httpServletResponse = (HttpServletResponse) response;
         httpServletResponse.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
         return;
      }
      chain.doFilter(request, response);
   }
}
```
Hipped answered 21/6, 2022 at 5:25 Comment(0)
S
2

Since this is the first result in Google and none of the answers has the full correct answer for Spring 2.7.x and beyond, this is what adding to application.properties fixed it for me:

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

# Tomcat properties
server.tomcat.max-http-form-post-size=10MB
server.tomcat.max-swallow-size=10MB
Scheelite answered 10/9, 2022 at 7:20 Comment(0)
N
1

For me this worked in yaml

spring:
    profiles: ....
    application:
        name:"...."
    http:
        multipart:
            max-file-size: 2147483648
            max-request-size: 2147483648
Neanderthal answered 27/2, 2020 at 8:14 Comment(0)
R
0

This worked for me with Tomcat 8

MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
ObjectName objectName = new ObjectName("Catalina:type=Connector,port=" + 8080);
mbeanServer.setAttribute(objectName, new Attribute("maxPostSize", 100000000));
Rayner answered 1/12, 2019 at 11:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.