springboot下载模板文件

springboot下载模板文件


我们经常需要将一些模板文件放在springboot项目里,并且通过接口能对这些文件进行下载。

1.文件位置

将模板文件放在/resources/template目录下,文件名称尽量不要用中文,防止线上环境出现编码问题。
在这里插入图片描述

2.controller层代码

    @RequestMapping("/downLoadTemplate")
    public void downLoadTemplate() {
            HttpServletResponse resp = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        templateService.downLoadTemplate(resp);
    }

3.service层代码

    public void downLoadTemplate(HttpServletResponse response) {
        //模板名称
        String templateName = "ceshimuban.xlsx";
        OutputStream out = null;
        InputStream input =null;
        try {
            ApplicationHome h = new ApplicationHome(getClass());
            String dirPath = h.getSource().toString();
            String fileName = dirPath+"/template/"+templateName;
            File outFile = new File(fileName);
            input = new BufferedInputStream(new FileInputStream(outFile));
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String((templateName).getBytes(), "iso-8859-1"));
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            out = response.getOutputStream();
            byte[] buffer = new byte[1024]; // 缓冲区
            int bytesToRead = -1;
            // 通过循环将读入内容输出到浏览器中
            while ((bytesToRead = input.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } catch (IOException e) {
            throw new BizException(new BizDict(UnicomResponseEnums.SYSTEM_ERROR.getCode(), "模板下载失败:" + e.getMessage()));
        } finally {
            IOUtils.closeQuietly(input);
            IOUtils.closeQuietly(out);
        }
    }   

这部分代码可替换
在这里插入图片描述

ResourceLoader resourceLoader = new DefaultResourceLoader();
            Resource resource = resourceLoader.getResource("classpath:template/"+templateName);
input =resource.getInputStream();

4.postman测试在这里插入图片描述

在这里插入图片描述

  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值