springboot下载模板文件

该代码片段展示了一个Java方法,用于从resources目录下的/excel/模板.xlsx路径下载模板文件到客户端。它使用ClassPathResource读取文件,设置HttpServletResponse以octet-stream类型返回,并通过URLEncoder处理文件名以适应UTF-8编码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

模板文件放在resources目录下
在这里插入图片描述

public void downloadTemplate(HttpServletResponse response) {
        String path = "/excel/模板.xlsx";
        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            ClassPathResource classPathResource = new ClassPathResource(path);
            if (!classPathResource.exists()) {
                throw new Exception("模板不存在");
            }
            //读取要下载的文件,保存到文件输入流
            inputStream = classPathResource.getInputStream();
            outputStream = response.getOutputStream();

            response.reset();
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("模板.xlsx", "utf-8"));

            byte[] buff = new byte[1024];
            int i = 0;
            while ((i = inputStream.read(buff)) != -1) {
                outputStream.write(buff, 0, i);
                outputStream.flush();
            }
        } catch (Exception e) {
            throw new Exception("模板下载失败");
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                throw new Exception("模板下载失败");
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值