设为首页 加入收藏

TOP

SpringBoot3文件管理(一)
2023-08-26 21:11:19 】 浏览:59
Tags:SpringBoot3 文件管

标签:上传.下载.Excel.导入.导出;

一、简介

在项目中,文件管理是常见的复杂功能;

首先文件的类型比较多样,处理起来比较复杂,其次文件涉及大量的IO操作,容易引发内存溢出;

不同的文件类型有不同的应用场景;

比如:图片常用于头像和证明材料;Excel偏向业务数据导入导出;CSV偏向技术层面数据搬运;PDF和Word用于文档类的材料保存等;

下面的案例只围绕普通文件Excel两种类型进行代码实现;

二、工程搭建

1、工程结构

2、依赖管理

普通文件的上传下载,依赖spring-boot框架即可,而Excel类型选择easyexcel组件,该组件内部依赖了apache-poi组件的4.1.2版本;

<!-- 基础框架组件 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>${spring-boot.version}</version>
</dependency>

<!-- Excel组件 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>${easyexcel.version}</version>
    <exclusions>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </exclusion>
    </exclusions>
</dependency>

三、上传下载

1、配置管理

在配置文件中,添加max-file-size单个文件大小限制和max-request-size请求最大限制两个核心参数;

需要说明的一点是:如何设定参数值的大小,与业务场景和服务器的处理能力都有关系,在测试的过程中优化即可;

spring:
  # 文件配置
  servlet:
    multipart:
      enabled: true
      # 文件单个限制
      max-file-size: 10MB
      # 请求最大限制
      max-request-size: 20MB

2、上传下载

这里提供一个文件批量上传接口和一个文件下载接口,把文件管理在工程中的resources/file目录下,下载接口中需要指定该目录下的文件名称;

@RestController
public class FileWeb {
    private static final Logger logger = LoggerFactory.getLogger(FileWeb.class);
    @Resource
    private FileService fileService ;

    /**
     * 文件上传
     */
    @PostMapping("/file/upload")
    public String upload (HttpServletRequest request,
                          @RequestParam("file") MultipartFile[] fileList) throws Exception {
        String uploadUser = request.getParameter("uploadUser");
        if (uploadUser.isEmpty()){
            return "upload-user is empty";
        }
        logger.info("upload-user:{}",uploadUser);
        for (MultipartFile multipartFile : fileList) {
            // 解析文件信息和保存
            fileService.dealFile(multipartFile);
        }
        return "success" ;
    }
    /**
     * 文件下载
     */
    @GetMapping("/file/download")
    public void upload (@RequestParam("fileName") String fileName,
                        HttpServletResponse response) throws Exception {
        if (!fileName.isBlank()){
            String filePath = ResourceUtils.getURL("m1-04-boot-file/src/main/resources/file").getPath();
            File file = new File(filePath,fileName) ;
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
            response.setContentType("application/octet-stream");
            Files.copy(Paths.get(file.getPath()), response.getOutputStream());
        }
    }
}

/**
 * 文件服务类
 */
@Service
public class FileService {

    private static final Logger logger = LoggerFactory.getLogger(FileService.class);

    public void dealFile (MultipartFile multipartFile) throws Exception {
        logger.info("Name >> {}",multipartFile.getName());
        logger.info("OriginalFilename >> {}",multipartFile.getOriginalFilename());
        logger.info("ContentType >> {}",multipartFile.getContentType());
        logger.info("Size
首页 上一页 1 2 3 下一页 尾页 1/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇hibernate入门 下一篇10、Spring之AOP概述

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目