【常用知识点-Java】Springboot上传Excel并存放到本地

复制代码
Author:赵志乾
Date:2024-07-04
Declaration:All Right Reserved!!!

1. 添加依赖

在pom.xml中添加excel文件处理库。

复制代码
<!-- Apache POI for Excel processing -->  
<dependency>  
    <groupId>org.apache.poi</groupId>  
    <artifactId>poi</artifactId>  
    <version>5.2.3</version>  
</dependency>  
<dependency>  
    <groupId>org.apache.poi</groupId>  
    <artifactId>poi-ooxml</artifactId>  
    <version>5.2.3</version>  
</dependency>

2. 配置上传相关参数

application.yml中配置文件上传的大小限制。

复制代码
spring:
  servlet:
    multipart:
      max-file-size: 20MB
      max-request-size: 20MB

3. 创建Controller接收文件并保存到本地

复制代码
@RestController
@RequestMapping("/api/excel")
public class ExcelUploadController {

    private final String TARGET_FOLDER = "./";

    @PostMapping("/upload")
    public ResponseEntity<String> uploadExcelFile(@RequestParam("file") MultipartFile file, @RequestParam("traceId")String traceId) {
        if (file.isEmpty()) {
            return ResponseEntity.status(400).body("File is empty");
        }

        try {
            // 确保多级目录存在
            String filePathName = TARGET_FOLDER+traceId+"/";
            File filePath = new File(filePathName);
            if(!filePath.exists()){
                boolean result = filePath.mkdirs();
                if(!result){
                    return ResponseEntity.status(500).body("Failed to process Excel file");
                }
            }
            // 文件保存到本地
            String fileName = file.getOriginalFilename();
            Path path = Paths.get(TARGET_FOLDER +traceId+"/"+ fileName).normalize();
            Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);

            return ResponseEntity.ok("Excel file uploaded and processed successfully");
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("Failed to process Excel file");
        }
    }
}
相关推荐
阿豪只会阿巴11 分钟前
【没事学点啥】TurboBlog轻量级个人博客项目——Turbo Blog 项目学习与上线指南
开发语言·python·学习·状态模式
幸运的大号暖贴14 分钟前
解决Vibe Coding时Idea经常不自动git add问题
java·人工智能·git·intellij-idea·claudecode·opencode
m0_7162550022 分钟前
第一部分 数据开发 面试全题 模拟口述版(自问自答)
java·数据库·面试
Non-existent98724 分钟前
TableGIS的WPS扩展项插件-通信网优规划相关地理空间数据处理
数据分析·excel·wps
L-影27 分钟前
常见的 ORM 工具
开发语言·数据库·fastapi·orm
azhou的代码园34 分钟前
基于SpringBoot+Vue的家教小程序
vue.js·spring boot·小程序·毕业设计·家教小程序
飞Link38 分钟前
构筑你的数字第二大脑:Obsidian 深度解析与配置指南
开发语言·python
SuperherRo1 小时前
服务攻防-Java组件安全&FastJson&高版本JNDI&不出网C3P0&编码绕WAF&写入文件CI链
java·安全·fastjson·waf·不出网·高版本·写入文件
彭于晏Yan1 小时前
Spring Boot 聚合MongoDB查询
spring boot·后端·mongodb
丑八怪大丑1 小时前
SQL数据类型
java·数据库·sql