spring-boot-route(三)实现多文件上传

本文介绍了如何在SpringBoot中配置文件上传大小限制,通过MultipartConfigElement设置单个文件和总文件大小。同时,讲解了如何将上传的文件存储到服务器物理路径,并映射到静态资源路径供访问。在前端,使用HTML表单实现文件上传,注意表单的enctype属性。此外,还展示了如何自定义静态资源路径,并提供了SpringBoot系列教程的目录链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

问题一:如何配置上传文件大小限制?

@Configuration
public class FileConfig implements WebMvcConfigurer {
    @Bean
    public MultipartConfigElement multipartConfigElement(){
        MultipartConfigFactory factory = new MultipartConfigFactory();
        // 单个文件大小
        factory.setMaxFileSize(DataSize.parse("10240MB"));
        // 上传的总文件大小
        factory.setMaxRequestSize(DataSize.parse("20480MB"));
        return factory.createMultipartConfig();
    }
}

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

@Configuration
public class FileConfig implements WebMvcConfigurer {

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

addResourceHandler(“/static/**”)表示访问路径为/static/文件名,addResourceLocations(“file:”+“D://uploadfile/”)表示文件存储的物理路径,"file:"为固定写法。

文件上传后台实现

@RestController
@Slf4j
public class FileUpload {

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

        // 存储上传成功的文件名,响应给客户端
        List<String> list = new ArrayList<>();
        // 判断文件数组长度
        if(files.length <= 0){
            list.add("请选择文件");
            return list;
        }
        for(MultipartFile file : files){
            // 源文件名
            String originalFilename = file.getOriginalFilename();
            // 文件格式
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 新文件名,避免文件名重复,造成文件替换问题
            String fileName = UUID.randomUUID()+"."+suffix;
            // 文件存储路径
            String filePath = "D:/uploadFile/";
            // 文件全路径
            File targetFile = new File(filePath+fileName);

            // 判断文件存储目录是否存在,不存在则新建目录
            if(!targetFile.getParentFile().exists()){
                targetFile.getParentFile().mkdir();
            }
            try {
                // 将图片保存
                file.transferTo(targetFile);
                list.add(originalFilename);
            } catch (IOException e) {
                log.info("文件上传异常={}",e);
            }
        }
        return list;
    }
}

静态资源问题

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

注:classpath 指的是 SpringBoot项目resources

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

application.yml中指定

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

代码实现WebMvcConfigurer

@Configuration
public class FileConfig implements WebMvcConfigurer {

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

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

文件上传前端实现

在静态资源路径下,新建file.html文件,浏览器访问ip:port/file.html,进入file页面

<form enctype="multipart/form-data" method="post" action="/uploadFile">
    文件:<input type="file" name="files"/>
    <input type="submit" value="上传"/>
</form>

这里需要注意的是文件上传表单的enctype为multipart/form-data

本文示例代码已上传至github,点个star支持一下!

更多优质内容推荐访问 毕设侠

### 如何通过 Maven 中央仓库下载 `spring-boot-starter-webflux` JAR 文件 可以通过访问 Maven 中央仓库来获取 `spring-boot-starter-webflux` 的依赖信息以及对应的 JAR 文件。以下是具体方法: #### 方法一:直接从 Maven 中央仓库下载 可以前往 Maven 中央仓库网站并搜索所需的依赖项。对于 `spring-boot-starter-webflux`,其官方页面位于以下链接[^3]: [Maven Central Repository - spring-boot-starter-webflux](https://search.maven.org/artifact/org.springframework.boot/spring-boot-starter-webflux) 在该页面中,找到对应版本的 JAR 文件下载链接,并手动下载。 #### 方法二:使用 Maven 命令安装到本地仓库 如果希望将 `spring-boot-starter-webflux` 安装至本地 Maven 仓库,则可以在项目的 `pom.xml` 文件中添加如下配置[^4]: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> <version>3.1.0</version> <!-- 替换为所需的具体版本 --> </dependency> ``` 运行以下命令即可自动下载并安装到本地 Maven 仓库: ```bash mvn clean install ``` #### 方法:手动指定路径安装 JAR 到本地仓库 如果已经拥有 `spring-boot-starter-webflux` 的 JAR 文件,可使用以下命令将其安装到本地 Maven 仓库[^5]: ```bash mvn install:install-file \ -Dfile=/path/to/jar/spring-boot-starter-webflux-3.1.0.jar \ -DgroupId=org.springframework.boot \ -DartifactId=spring-boot-starter-webflux \ -Dversion=3.1.0 \ -Dpackaging=jar ``` --- ### 示例代码片段 假设已成功引入 `spring-boot-starter-webflux`,下面是一个简单的 Spring Boot WebFlux 应用程序示例[^6]: ```java package com.example.webfluxdemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.ServerResponse; import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.web.reactive.function.server.RequestPredicates.GET; import static org.springframework.web.reactive.function.server.RouterFunctions.route; @SpringBootApplication public class WebfluxDemoApplication { public static void main(String[] args) { SpringApplication.run(WebfluxDemoApplication.class, args); } @Bean RouterFunction<ServerResponse> routeGreeting() { return route(GET("/greet"), request -> ServerResponse.ok() .contentType(APPLICATION_JSON) .bodyValue("Hello from WebFlux!")); } } ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java旅途

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值