【常用知识点-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");
        }
    }
}
相关推荐
Chengbei117 分钟前
JsOwl|AI 赋能 JS 敏感信息扫描器,AST + 正则、source‑map 源码还原、登录态爬虫输出交互式 HTML 报告
开发语言·javascript·网络·人工智能·爬虫·网络安全·自动化
David猪大卫9 分钟前
【C++修炼】string类:string类的模拟实现
c语言·开发语言·数据结构·c++·经验分享·笔记·学习
geovindu12 分钟前
rust: Iterator Pattern
开发语言·后端·设计模式·rust·行为模式·迭代器模
SDWAN_Cheap37 分钟前
深度解析什么是CDN加速:从原理到实践的技术拆解
开发语言·cdn加速
鬼手点金38 分钟前
模型即 Agent:当模型本身成为产品
开发语言·前端·人工智能·python·机器学习
SunnyDays10111 小时前
如何使用 Java 提取 PPT 中的文字:整份文档、指定幻灯片与表格内容
java·powerpoint
毕设单片机1 小时前
springboot志愿服务平台的设计与实现 36731
java·spring boot·mysql·志愿服务平台
染指11101 小时前
147.Agent-LangGraph归并函数
开发语言·人工智能·python·langchain·agents
IT_Octopus1 小时前
【零基础入门 LLM 开发 · Day 15】:LangChain 注册工具——告别手写 JSON Schema
java·langchain·json