By default, the size of a single uploaded file is 1MB, and the total size of a uploaded file is 10MB.

Single file uploads use the MultipartFile parameter to receive the file, and multiple files use the MultipartFile[] array to receive the file, and then iterate over it as if it were a single file.

Question 1: How do I set the maximum size for uploaded files?

@Configuration
public class FileConfig implements WebMvcConfigurer {
    @Bean
    public MultipartConfigElement multipartConfigElement(a){
        MultipartConfigFactory factory = new MultipartConfigFactory();
        // Single file size
        factory.setMaxFileSize(DataSize.parse("10240MB"));
        // Total file size uploaded
        factory.setMaxRequestSize(DataSize.parse("20480MB"));
        returnfactory.createMultipartConfig(); }}Copy the code

Consider: The SpringBoot project recommends using jar packages to run projects, and in practice we have found that jar packages are more convenient to run projects. However, when the jar package is finished, the size of the JAR is fixed, and the uploaded file cannot be transferred to the JAR package. SpringBoot provides a way to upload a file to the physical path of the server and then perform a mapping to ensure that the image can be accessed normally. The operations are as follows:

@Configuration
public class FileConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {        registry.addResourceHandler("/static/**").addResourceLocations("file:"+"D://uploadfile/"); }}Copy the code

AddResourceHandler (“/static/**”) indicates the access path to /static/ file name. AddResourceLocations (“file:”+”D:// uploadFile /”) indicates the physical path to store the file. “File :” is a fixed notation.

File upload background implementation

@RestController
@Slf4j
public class FileUpload {

    @PostMapping("uploadFile")
    public List uploadFile(@RequestParam("files") MultipartFile[] files) {

        // Stores the name of the file successfully uploaded and responds to the client
        List<String> list = new ArrayList<>();
        // Determine the size of the file array
        if(files.length <= 0){
            list.add("Please select file");
            return list;
        }
        for(MultipartFile file : files){
            // Source file name
            String originalFilename = file.getOriginalFilename();
            // File format
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            // New file name to avoid file replacement problems
            String fileName = UUID.randomUUID()+"."+suffix;
            // File storage path
            String filePath = "D:/uploadFile/";
            // Full file path
            File targetFile = new File(filePath+fileName);

            // Check whether the file storage directory exists. If no, create a new directory
            if(! targetFile.getParentFile().exists()){ targetFile.getParentFile().mkdir(); }try {
                // Save the image
                file.transferTo(targetFile);
                list.add(originalFilename);
            } catch (IOException e) {
                log.info("Abnormal file upload ={}",e); }}returnlist; }}Copy the code

Static resource problem

SpringBoot The default path for static resources is classpath:/ meta-INF /resources/, classpath:/resources/, classpath:/static/, classpath:/public/. That is, if you want to access static resources, you need to put the static resource files under these four paths.

Note: Classpath refers to SpringBoot resources

If you want to customize static resource paths there are two ways,

Application. Yml specified

spring:
  resources:
    static-locations: classpath:/templates/
Copy the code

Code to achieve WebMvcConfigurer

@Configuration
public class FileConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/ * *").addResourceLocations("classpath:/templates/");
    }
Copy the code

Note: After a static resource path is configured, the default configuration is invalid

File upload front-end implementation

In the static resource path, create file file. HTML and access the IP address :port/file. HTML to go to the file page

<form enctype="multipart/form-data" method="post" action="/uploadFile">File:<input type="file" name="files"/>
    <input type="submit" value="Upload"/>
</form>
Copy the code

Note here that the encType of the file upload form is multipart/form-data.


The sample code for this article has been uploaded togithub, point astarSupport!

Spring Boot series tutorial directory

Spring-boot-route (I) Several ways for Controller to receive parameters

Spring-boot-route (2) Several methods of reading configuration files

Spring-boot-route (3) Upload multiple files

Spring-boot-route (4) Global exception processing

Spring-boot-route (5) Integrate Swagger to generate interface documents

Spring-boot-route (6) Integrate JApiDocs to generate interface documents

Spring-boot-route (7) Integrate jdbcTemplate operation database

Spring-boot-route (8) Integrating mybatis operation database

Spring-boot-route (9) Integrate JPA operation database

Spring-boot-route (10) Switching between multiple data sources

Spring-boot-route (11) Encrypting database configuration information

Spring-boot-route (12) Integrate REDis as cache

Spring-boot-route RabbitMQ

Spring-boot-route Kafka

Spring-boot-route (15) Integrate RocketMQ

Spring-boot-route (16) Use logback to produce log files

Spring-boot-route (17) Use AOP to log operations

Spring-boot-route (18) Spring-boot-adtuator monitoring applications

Spring-boot-route (19) Spring-boot-admin Monitoring service

Spring-boot-route (20) Spring Task Implements simple scheduled tasks

Spring-boot-route (21) Quartz Implements dynamic scheduled tasks

Spring-boot-route (22) Enables email sending

Spring-boot-route (23) Developed wechat official accounts

Spring-boot-route (24) Distributed session consistency processing

Spring-boot-route (25) two lines of code to achieve internationalization

Spring-boot-route (26) Integrate webSocket

This series of articles are frequently used in the work of knowledge, after learning this series, to cope with daily development more than enough. If you want to know more, just scan the qr code below and let me know. I will further improve this series of articles!