【常用知识点-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");
        }
    }
}
相关推荐
摇滚侠12 分钟前
帮我整理一份 IDEA 开发中常用快捷键
java·ide·intellij-idea
向宇it21 分钟前
php高性能的导出excel读写扩展——xlswriter,比传统的Spreadsheet要快很多
php·excel·xlswriter
赵侃侃爱分享25 分钟前
学完Python第一次写程序写了这个简单的计算器
开发语言·python
断眉的派大星40 分钟前
# Python 魔术方法(魔法方法)超详细讲解
开发语言·python
2501_9333295543 分钟前
技术深度拆解:Infoseek舆情处置系统的全链路架构与核心实现
开发语言·人工智能·自然语言处理·架构
妮妮喔妮1 小时前
supabase的webhook报错
开发语言·前端·javascript
我的xiaodoujiao1 小时前
API 接口自动化测试详细图文教程学习系列11--Requests模块3--测试练习
开发语言·python·学习·测试工具·pytest
疯狂成瘾者1 小时前
YAML配置介绍
java
cccccc语言我来了1 小时前
C++轻量级消息队列服务器
java·服务器·c++
better_liang1 小时前
每日Java面试场景题知识点之-MCP协议在Java开发中的应用实践
java·spring boot·ai·mcp·企业级开发