【常用知识点-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");
        }
    }
}
相关推荐
云游云记1 分钟前
php Composer 使用全攻略
开发语言·php·composer
码农水水7 分钟前
SpringBoot配置优化:Tomcat+数据库+缓存+日志全场景教程
java·数据库·spring boot·后端·算法·tomcat·哈希算法
毕设源码-朱学姐7 分钟前
【开题答辩全过程】以 基于ssm的电影推荐与分享平台的设计与实现为例,包含答辩的问题和答案
java
独自破碎E11 分钟前
LCR004-只出现一次的数字II
java·开发语言
剑锋所指,所向披靡!13 分钟前
STL之sting容器
开发语言·c++
Henry Zhu12314 分钟前
Qt Model/View架构详解(六):综合实战项目(下)
开发语言·qt·架构
Elias不吃糖15 分钟前
Spring Bean 注入与容器管理:从“怎么交给容器”到“怎么被注入使用”的完整总结
java·spring·rpc·bean
要做一个小太阳15 分钟前
excel VLOOKUP函数
excel
Liuqz200919 分钟前
Go 安装与配置
开发语言·后端·golang
2301_7657031420 分钟前
动态库热加载技术
开发语言·c++·算法