Set file upload size limit in Spring Boot

In Spring Boot, you can set the size of the uploaded file by following these steps:

In the application.properties or application.yml file, add the following configuration:
For application.properties:

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

For application.yml:

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

Here max-file-size is the maximum size of a single file, and max-request-size is the maximum size of the entire request. These values ​​can be adjusted as needed.

If you are using Spring Boot 1.x version, you also need to add the MultipartConfigElement annotation to the startup class, as shown below:

java

import org.springframework.boot.web.servlet.MultipartConfigFactory;  
import javax.servlet.MultipartConfigElement;  
  
@SpringBootApplication  
public class YourApplication {
    
      
  
    public static void main(String[] args) {
    
      
        SpringApplication.run(YourApplication.class, args);  
    }  
  
    @Bean  
    public MultipartConfigElement multipartConfigElement() {
    
      
        MultipartConfigFactory factory = new MultipartConfigFactory();  
        factory.setMaxFileSize("128MB");  
        factory.setMaxRequestSize("128MB");  
        return factory.createMultipartConfig();  
    }  
}

However, starting with Spring Boot 2.x, this step is no longer necessary because Spring Boot automatically configures these properties.

Through the above configuration, you can limit the file upload size in Spring Boot applications. It should be noted that these restrictions are not done on the client side, but on the server side. Therefore, even if the client attempts to upload a file that exceeds the limit, the problem will only be discovered after the file has been uploaded to the server. In actual applications, corresponding checks and prompts may also be required on the client side.

Guess you like

Origin blog.csdn.net/qq_22744093/article/details/134590262