【常用知识点-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");
        }
    }
}
相关推荐
秋邱2 分钟前
Java面向对象进阶实战:用工厂模式+策略模式优化支付系统
java·bash·策略模式
leiming66 分钟前
c++ 容器 queue
开发语言·c++
CSDN_RTKLIB10 分钟前
【类定义系列三】内联函数进阶
开发语言·c++
heartbeat..17 分钟前
网络通信核心知识全解析:模型、协议与 TCP 机制
java·网络·网络协议·tcp/ip
北京流年22 分钟前
执行clang --version报错说由于找不到 libgcc_s_seh-1.dll和 找不到 libstdc++-6.dll 这两个文件
开发语言·c++
q_191328469524 分钟前
基于SpringBoot+Vue.js的高校竞赛活动信息平台
vue.js·spring boot·后端·mysql·程序员·计算机毕业设计
weixin_4407305031 分钟前
Java基础学习day01
java·开发语言·学习
军军君0141 分钟前
Three.js基础功能学习一:环境资源及基础知识
开发语言·javascript·学习·3d·前端框架·threejs·三维
是垚不是土1 小时前
基于DDNS-Go动态域名解析配置:实现多网络线路冗余切换方案
运维·开发语言·网络·阿里云·golang·运维开发
野比带雄1 小时前
対excel时间格式的理解
excel