【常用知识点-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");
        }
    }
}
相关推荐
百***06944 分钟前
Skywalking介绍,Skywalking 9.4 安装,SpringBoot集成Skywalking
spring boot·后端·skywalking
小二·7 分钟前
Elasticsearch 面试题精编(26题|含答案|分类整理)
java·大数据·elasticsearch
BD_Marathon15 分钟前
在 Linux 环境中配置 Eclipse 以开发 Hadoop 应用
java·hadoop·eclipse
百***374816 分钟前
Spring Boot 中 RabbitMQ 的使用
spring boot·rabbitmq·java-rabbitmq
草莓熊Lotso29 分钟前
C++ 二叉搜索树(BST)完全指南:从概念原理、核心操作到底层实现
java·运维·开发语言·c++·人工智能·经验分享·c++进阶
oliveira-time38 分钟前
单例模式中的饿汉式
java·开发语言
凌波粒41 分钟前
SpringMVC基础教程(1)--MVC/DispathcerServlet
java·spring·mvc
武子康41 分钟前
Java-173 Neo4j + Spring Boot 实战:从 Driver 到 Repository 的整合与踩坑
java·数据库·spring boot·后端·spring·nosql·neo4j
凌波粒43 分钟前
SpringMVC基础教程(2)--Controller/RestFul风格/JSON/数据转发和重定向
java·后端·spring·json·restful
老鼠只爱大米2 小时前
Java 设计模式之适配器模式:系统集成的万能接口
java·设计模式·适配器模式·adapter·java设计模式