【常用知识点-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");
        }
    }
}
相关推荐
yuzhiboyouye5 小时前
《阿里巴巴 Java 开发手册》的 MySQL 核心规范
java·开发语言·mysql
郝学胜-神的一滴6 小时前
Effective STL 条款12:对容器线程安全性的现实期望
c语言·开发语言·c++·qt·网络协议·rpc·numpy
geovindu6 小时前
python: KNeighborsClassifier K
开发语言·后端·python·算法
秋饼6 小时前
Spring AI 2.0 渐进式工具披露实战:ToolSearchToolCallingAdvisor 源码机制、四种 ToolIndex 选型与多租户踩坑
java·ai·技术分享·后端开发
时间的情敌8 小时前
Three.js 射线拾取进阶:hover 高亮、点击弹窗、多物体过滤、穿透拾取
开发语言·javascript·three.js
Amumu121388 小时前
TypeScript学习: 基本类型(一)
开发语言·前端·typescript
迦蓝叶9 小时前
自建 MaaS 卡住的地方从来不是模型:JAiRouter 开源 AI 网关的四个答案
人工智能·spring boot·开源·架构设计·maas·ai 网关
头发还在的女程序员9 小时前
家政小程序系统源码IM已读记录:多端阅读状态怎样保持单调推进
java·spring boot·源码·家政·消息同步
敲上瘾9 小时前
Qt 常用控件:按钮、显示输入、容器与布局等
开发语言·c++·qt·qt6.3
船神丿男人9 小时前
C++ STL 入门:用 std::string 读配置,四个容易漏掉的边界
开发语言·c++