首页 > 其他分享 >SpringBoot3文件管理

SpringBoot3文件管理

时间:2023-08-10 09:00:09浏览次数:34  
标签:文件 String 管理 Excel class DataVO SpringBoot3 file public

目录

标签:上传.下载.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 >> {}",multipartFile.getSize());
        // 文件输出地址
        String filePath = ResourceUtils.getURL("m1-04-boot-file/src/main/resources/file").getPath();
        File writeFile = new File(filePath, multipartFile.getOriginalFilename());
        multipartFile.transferTo(writeFile);
    }
}

使用Postman测试文件批量上传接口:

四、Excel文件

1、Excel创建

基于easyexcel组件中封装的EasyExcel工具类,继承自EasyExcelFactory工厂类,实现Excel单个或多个Sheet的创建,并且在单个Sheet中写多个Table数据表;

@Service
public class ExcelService {
    /**
     * Excel-写单个Sheet
     */
    public static void writeSheet () throws Exception {
        // 文件处理
        String basePath = getAbsolutePath();
        File file = new File(basePath+"/easy-excel-01.xlsx") ;
        checkOrCreateFile(file);
        // 执行写操作
        EasyExcel.write(file).head(DataVO.class)
                .sheet(0,"用户信息").doWrite(DataVO.getSheet1List());
    }
    /**
     * Excel-写多个Sheet
     */
    public static void writeSheets () throws Exception {
        // 文件处理
        String basePath = getAbsolutePath();
        File file = new File(basePath+"/easy-excel-02.xlsx") ;
        checkOrCreateFile(file);
        ExcelWriter excelWriter = null;
        try {
            excelWriter = EasyExcel.write(file).build();
            // Excel-Sheet1
            WriteSheet writeSheet1 = EasyExcel.writerSheet(0,"分页1").head(DataVO.class).build();
            // Excel-Sheet2
            WriteSheet writeSheet2 = EasyExcel.writerSheet(1,"分页2").head(DataVO.class).build();
            // Excel-Sheet3,写两个Table
            WriteSheet writeSheet3 = EasyExcel.writerSheet(2,"分页3").build();
            WriteTable dataTable = EasyExcel.writerTable(0).head(DataVO.class).build();
            WriteTable dataExtTable = EasyExcel.writerTable(1).head(DataExtVO.class).build();
            // 执行写操作
            excelWriter.write(DataVO.getSheet1List(), writeSheet1);
            excelWriter.write(DataVO.getSheet2List(), writeSheet2);
            excelWriter.write(DataVO.getSheet1List(),writeSheet3,dataTable) ;
            excelWriter.write(DataExtVO.getSheetList(),writeSheet3,dataExtTable) ;
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            if (excelWriter != null){
                excelWriter.close();
            }
        }
    }
}

/**
 * 实体类,这里的注解会解析为Excel中的表头
 */
public class DataVO {
    @ExcelProperty("编号")
    private Integer id ;
    @ExcelProperty("名称")
    private String name ;
    @ExcelProperty("手机号")
    private String phone ;
    @ExcelProperty("城市")
    private String cityName ;
    @ExcelProperty("日期")
    private Date date ;
}

文件效果:

2、Excel读取

对于读取Excel文件来说,则需要根据具体的样式来定了,在easyexcel组件中还可以添加读取过程的监听器;

@Service
public class ExcelService {
    /**
     * Excel-读取数据
     */
    public static void readExcel () throws Exception {
        // 文件处理
        String basePath = getAbsolutePath();
        File file = new File(basePath+"/easy-excel-01.xlsx") ;
        if (!file.exists()){
            return ;
        }
        // 读取数据
        List<DataVO> dataList = EasyExcel.read(file).head(DataVO.class)
                .sheet(0).headRowNumber(1).doReadSync();
        dataList.forEach(System.out::println);
    }
    /**
     * Excel-读取数据使用解析监听器
     */
    public static void readExcelListener () throws Exception {
        // 文件处理
        String basePath = getAbsolutePath();
        File file = new File(basePath+"/easy-excel-01.xlsx") ;
        if (!file.exists()){
            return ;
        }
        // 读取数据,并且使用解析监听器
        DataListener dataListener = new DataListener() ;
        List<DataVO> dataSheetList = EasyExcel.read(file,dataListener).head(DataVO.class)
                .sheet(0).headRowNumber(1).doReadSync();
        dataSheetList.forEach(System.out::println);
    }
}

3、解析监听

继承AnalysisEventListener类,并重写其中的方法,可以监听Excel的解析过程,或者添加一些自定义的处理逻辑;

public class DataListener extends AnalysisEventListener<DataVO> {
    /**
     * 接收解析的数据块
     */
    @Override
    public void invoke(DataVO data, AnalysisContext context) {
        System.out.println("DataListener:"+data);
    }
    /**
     * 接收解析的表头
     */
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        System.out.println("DataListener:"+headMap);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        System.out.println("DataListener:after...all...analysed");
    }
}

4、导入导出

实际上Excel文件的导入导出,原理与文件的上传下载类似,只不过这里使用easyexcel组件中的API来直接处理Excel的写和读;

@RestController
public class ExcelWeb {

    @GetMapping("excel/download")
    public void download(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("Excel数据", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), DataVO.class).sheet("用户").doWrite(DataVO.getSheet1List());
    }

    @ResponseBody
    @PostMapping("excel/upload")
    public String upload(@RequestParam("file") MultipartFile file) throws IOException {
        List<DataVO> dataList = EasyExcel
                .read(file.getInputStream(), DataVO.class, new DataListener()).sheet().doReadSync();
        dataList.forEach(System.out::println);
        return "success";
    }
}

使用Postman测试单个Excel上传接口:

五、参考源码

文档仓库:
https://gitee.com/cicadasmile/butte-java-note

源码仓库:
https://gitee.com/cicadasmile/butte-spring-parent

标签:文件,String,管理,Excel,class,DataVO,SpringBoot3,file,public
From: https://www.cnblogs.com/cicada-smile/p/17619352.html

相关文章

  • 这些命令可以直接在Windows资源管理器的地址栏中输入,或通过运行对话框(Win + R)中输入运
    Windowsshell命令和路径:shell:commonstartup:该命令用于打开"公共启动"文件夹,这是一个用于存放所有计算机用户启动项的文件夹。在这个文件夹中放置的程序或快捷方式会在每个用户登录时自动执行。shell:sendto:这个命令用于打开"发送到"菜单的文件夹,它包含了在右键菜单中"发送到"......
  • 【看表情包学Linux】初识文件描述符 | 虚拟文件系统 (VFS) 初探 | 系统传递标记位 | O
    爆笑教程《看表情包学Linux》......
  • 【看表情包学Linux】系统下的文件操作 | 文件系统接口 | 系统调用与封装 | open,write
      ......
  • startup_ch32v00x.S启动文件分析(上)
    引言CH32系列MCU是由南京沁恒(WCH)公司推出的一系列处理器芯片。引自官网:CH32V、CH32X、CH32L系列MCU采用自研的青稞RISC-V内核,基于蓬勃发展的RISC-V开源指令集架构,针对低功耗和高速响应等应用优化扩展,免费配套IDE等开发工具软件,免除第三方内核技术的授权费和提成费,通过内置和组......
  • Visual Studio中属性表.props文件的复用
    最近在Windows下配置用于支持C++的OpenCV、GDAL、Eigen环境,最开始用mingw按照sqlite3-tiff-jpeg-proj-gdal的顺序编译GDAL,十分痛苦。后来索性使用Microsoft自家的VisualStudio,拷贝别人编译好的GDAL和OpenCV以及Eigen库,终于配置完成。VisualStudio每次新建项目都要在属性表中......
  • 解密SpringBoot3.0:构建易维护的JavaWeb应用
    SpringBoot3.0最新深入浅出从入门到项目实战,突出Web应用痛点解决方案SpringBoot已经成为Java开发中最流行的框架之一,它提供了一种快速构建、易于扩展的方式,使开发人员能够更加专注于业务逻辑而不是繁琐的配置。而最新的SpringBoot3.0版本将进一步改善开发体验,并提供更多的解决方......
  • java 定时任务实现 每隔10天 删除指定文件夹下的文件
    使用ScheduledExecutorService实现要在Java中实现每隔10天删除文件夹下的文件,可以使用定时任务来执行此操作。可以使用Java中的ScheduledExecutorService类来创建和管理定时任务,并使用File类来删除文件。示例代码,用于实现每隔10天删除文件夹下的文件:importjava.io.File;......
  • C语言驱动开发之内核解锁与强删文件
    在某些时候我们的系统中会出现一些无法被正常删除的文件,如果想要强制删除则需要在驱动层面对其进行解锁后才可删掉,而所谓的解锁其实就是释放掉文件描述符(句柄表)占用,文件解锁的核心原理是通过调用ObSetHandleAttributes函数将特定句柄设置为可关闭状态,然后在调用ZwClose将其文件关闭......
  • go-zero 是如何做路由管理的?
    原文链接:go-zero是如何做路由管理的?go-zero是一个微服务框架,包含了web和rpc两大部分。而对于web框架来说,路由管理是必不可少的一部分,那么本文就来探讨一下go-zero的路由管理是怎么做的,具体采用了哪种技术方案。路由管理方案路由管理方案有很多种,具体应该如何选择,应......
  • sudo apt update 报错:库 “https://download.docker.com/linux/ubuntu \ Release”
    sudoaptupdate报错:错误:10https://download.docker.com/linux/ubuntu\Release404NotFound[IP:143.204.126.13443]命中:11http://ppa.launchpad.net/rock-core/qt4/ubuntufocalInRelease命中:12https://dl.google.com/linux/chrome/debstableInRelease正......