【常用知识点-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");
        }
    }
}
相关推荐
谙忆10 分钟前
PNG改成ICO为什么不能用:用Python检查多尺寸目录与256px帧
开发语言·python
萧瑟余晖11 分钟前
Spring Data综合实战与调优详解
java·后端·spring
青峰讲运维20 分钟前
OpenStack 存储深度解析|Cinder 块存储 + Swift 对象存储原理与完整实操(Yoga)
开发语言·openstack·swift
汤姆宝库25 分钟前
具身智能深拆:VLA、世界模型与数据飞轮
开发语言·人工智能·php
云和数据.ChenGuang32 分钟前
深入剖析 Python 的 MRO 规则:从 C3 线性化到实战踩坑
开发语言·python·1024程序员节
123_不打狼42 分钟前
Squidiff:基于条件扩散模型预测细胞发育与扰动响应
开发语言·python·squidiff
yuniko-n1 小时前
【JUC】原子类 LongAdder
java
瑞got1 小时前
java使用CountDownLatch做并行查询
java·开发语言
aiks_yuan1 小时前
Spring AI MCP Server 怎么接入 Claude Code:Spring Boot 用 @McpTool 暴露接口(Spring AI 2.0.2 实测)
spring boot