多文件上传

文件大小配置

Spring Boot默认上传的单个文件大小1MB,一次上传的总文件大小为10MB

单个文件上传使用MultipartFile参数来接收文件,多文件使用MultipartFile[]数组来接收,然后遍历它,当成单文件来处理。

由于springboot具有几个版本,不同版本对于文件上传最大限制的配置也有所不同。

所以要注意springboot本身的版本,不然会一直报错

在springboot1.3版本中:

multipart.maxFileSize

在springboot1.4与springboot1.5版本中:

spring.http.multipart.max-file-size

在springboot2.0版本中:

# 最大上传单个文件大小:默认1M
spring.servlet.multipart.max-file-size=1024MB
# 设置最大总上传的数据大小 :默认10M
spring.servlet.multipart.max-request-size=1024MB

MultipartProperties源码version-1.5.10:

package org.springframework.boot.autoconfigure.web;

@ConfigurationProperties(prefix = "spring.http.multipart", ignoreUnknownFields = false)
public class MultipartProperties {

	/**
	 * Enable support of multipart uploads.
	 */
	private boolean enabled = true;

	/**
	 * Intermediate location of uploaded files.
	 */
	private String location;

	/**
	 * Max file size. Values can use the suffixes "MB" or "KB" to indicate megabytes or
	 * kilobytes respectively.
	 */
	private String maxFileSize = "1MB";

	/**
	 * Max request size. Values can use the suffixes "MB" or "KB" to indicate megabytes or
	 * kilobytes respectively.
	 */
	private String maxRequestSize = "10MB";
}

代码🌰

springboot-1.5.10:application.properties

# 最大上传单个文件大小:默认1M
spring.http.multipart.maxFileSize=3MB
# 最大置总上传的数据大小 :默认10M
spring.http.multipart.maxRequestSize=5MB

也可以在配置类中设置文件大小,与上面配置文件方式两者二选一即可。

@Configuration
public class FileConfig extends WebMvcConfigurerAdapter {
    @Bean
    public MultipartConfigElement multipartConfigElement(){
        MultipartConfigFactory factory = new MultipartConfigFactory();
        // 单个文件大小
        factory.setMaxFileSize("1MB");
        // 上传的总文件大小
        factory.setMaxRequestSize("20MB");
        return factory.createMultipartConfig();
    }
}
@RestController
@RequestMapping("/curl-test")
public class DemoController {
    @PostMapping("upload-file")
    public RestResult uploadFile(@RequestParam("files") MultipartFile[] files) {
        int length = files.length;
        if (length < 0) {
            return RestResult.failResult("文件不能为空");
        }

        for (MultipartFile file : files) {
            // 源文件名
            String filename = file.getOriginalFilename();

            // 文件格式(扩展名)
            String suffix = filename.substring(filename.lastIndexOf("."));

            String newFileName = UUID.randomUUID() + suffix;

            // 文件存储路径(注意这里image目录后一定要写\\,指定是在image目录下,否则会保存到父目录)
            String filePath = "F:\\code\\demo\\image\\";

            // 文件全路径
            File targetFile = new File(filePath + newFileName);

            // 判断文件存储目录是否存在,不存在则新建目录
            if (!targetFile.getParentFile().exists()) {
                targetFile.getParentFile().mkdir();
            }

            try {
                // 将图片保存
                file.transferTo(targetFile);
            } catch (IOException e) {
                // log.info("文件上传异常:{}",e);
            }
        }
        return RestResult.successResult();
    }
}

SpringBoot项目推荐使用jar包的方式来运行项目,而实际应用中我们也发现jar包运行项目更加方便。但是当打完jar包后,这个jar的大小就固定好了,上传的文件肯定传不到jar包里面了。SpringBoot提供了一种方式,将文件上传到服务器物理路径下,然后做个映射关系,让图片可以正常被访问,具体操作如下:

方式一:配置类

@Configuration
public class FileConfig extends WebMvcConfigurerAdapter { // springboot 1.5.*版本
// public class FileConfig implements WebMvcConfigurer { // springboot 2.*版本

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // addResourceHandler("/static/**")表示访问路径为/static/文件名
        // addResourceLocations("file:"+"D://uploadfile/")表示映射的文件存储的物理路径,"file:"为固定写法。
        registry.addResourceHandler("/static/**")
            .addResourceLocations("file:" + "F:\\code\\demo\\image\\");
    }

}

此方式配置后,我们可以通过设置的访问路径访问我们上传到存储在本地文件

方式二:application.properties

# 配置本地服务器存储文件映射位置(并不是设置了保存文件时就不用配置文件路径)
spring.http.multipart.location=F:\\code\\demo\\image\\
# 本地上传文件的路径加入到静态资源路径中
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/, classpath:/static/, classpath:/public/, file:${spring.http.multipart.location}

此方式直接使用默认路径访问,不能像配置类中可以指定访问路径,如:" /static/** "。(有大佬知道如何在配置文件中如何指定请评论,或者是不是只可以在配置类配置)

静态资源问题

SpringBoot静态资源默认路径为:classpath:/META-INF/resources/classpath:/resources/classpath:/static/classpath:/public/。也就是说如果想访问静态资源,则需要将静态资源 文件放在这四个路径下面。

注:classpath 指的是 SpringBoot项目resources

如果想自定义静态资源路径有两种方式:

application.yml中指定

spring:
  resources:
    static-locations: classpath:/templates/

配置类继承WebMvcConfigurerAdapter(springboot1.5.*版本,2.*.*版本是实现WebMvcConfigurer接口

@Configuration
public class FileConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/templates/");
    }
}

注:当配置了自定义静态资源路径后,其默认配置将失效

posted @ 2022-07-09 22:54  Lz_蚂蚱  阅读(711)  评论(0编辑  收藏  举报