当前位置:   article > 正文

SpringBoot下载resources目录下的文件

SpringBoot下载resources目录下的文件

1.引入SpringBoot和hutool依赖

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.22</version>
        </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

2.在项目resources目录下放入模版文件,结构如下:
在这里插入图片描述
3.定义文件下载接口

    @SneakyThrows(IOException.class)
    @ApiOperation(value = "下载模版文件", notes = "下载模版文件")
    @RequestMapping(value = "/down_template", method = RequestMethod.GET)
    public Response<Void> downTemplate(@RequestParam(required = false)String templateName, HttpServletResponse response) {
        if(StringUtils.isBlank(templateName)){
            return null;
        }
        response.setCharacterEncoding("utf-8");
        
        try (InputStream templateInputStream = this.getClass().getResourceAsStream("/template/" + templateName);
             OutputStream outputStream = response.getOutputStream()) {
            Asserts.notNull(templateInputStream, "templateInputStream is null");

            //获取文件字节数组
            byte[] bytes = IoUtil.readBytes(templateInputStream);
            //获取文件mimetype,也就是contenttype
            FileMagicNumber magicNumber = FileMagicNumber.getMagicNumber(bytes);
            if(magicNumber != FileMagicNumber.UNKNOWN){
                response.setContentType(magicNumber.getMimeType());
                String fileName = URLEncoder.encode("模版文件" + DateUtil.format(new Date(), "yyyyMMdd"), "UTF-8").replaceAll("\\+", "%20");
                response.setHeader("Content-disposition", "attachment; filename=" + fileName + "." + magicNumber.getExtension());
            }

            outputStream.write(bytes, 0, bytes.length);
        }
        return null;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

4.postman请求改接口,然后把文件流保存到本地目录,说明下载成功
在这里插入图片描述

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/小舞很执着/article/detail/960514
推荐阅读
相关标签
  

闽ICP备14008679号