SpringBoot 2.x版本+MultipartFile設置指定文件上傳大小


SpringBoot-versio:2.1.9-RELEASE

 

由於新版本的SpringBoot已經棄用了(1.5版本支持)如下,

 

 這種方式,提供了新的 配置方案。

 

這個是官方的介紹

 Handling Multipart File Uploads

Spring Boot embraces the Servlet 3 javax.servlet.http.Part API to support uploading files. By default, Spring Boot configures Spring MVC with a maximum size of 1MB per file and a maximum of 10MB of file data in a single request. You may override these values, the location to which intermediate data is stored (for example, to the /tmp directory), and the threshold past which data is flushed to disk by using the properties exposed in the MultipartProperties class. For example, if you want to specify that files be unlimited, set the spring.servlet.multipart.max-file-size property to -1.

The multipart support is helpful when you want to receive multipart encoded file data as a @RequestParam-annotated parameter of type MultipartFile in a Spring MVC controller handler method.

See the MultipartAutoConfiguration source for more details.

[Note]

It is recommended to use the container’s built-in support for multipart uploads rather than introducing an additional dependency such as Apache Commons File Upload.

 

 

方案一:

  application.properties配置(yml一樣,只是格式有變化)

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

 

方案二:

  編寫配置類,並通過@Bean標簽來加入到IOC容器中管理

package cn.arebirth.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;

import javax.servlet.MultipartConfigElement;

@Configuration
public class FileUploadConfiuration {
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
 //單個文件大小200mb
        factory.setMaxFileSize(DataSize.ofMegabytes(200L));
        //設置總上傳數據大小10GB
        factory.setMaxRequestSize(DataSize.ofGigabytes(10L));

        return factory.createMultipartConfig();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM