SpringBoot实现文档下载

pom依赖:

<dependency>
	<groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.14</version>
</dependency>
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml-schemas</artifactId>
	<version>3.14</version>
</dependency>
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml</artifactId>
	<version>3.14</version>
</dependency>

HTML5 代码:

<input type="button" onclick="downTemplate()" value="下载模板" class="btn btn-primary"/>

JavaScript 代码:

<script type="text/javascript">
    var fileName = "学生信息模板.xlsx";
    function downTemplate() {
        window.open("/admin/downTemplate?fileName="+fileName);
    }
</script>

service层代码:

@Override
    public void downTemplate(String fileName) throws IOException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            HttpServletResponse response = requestAttributes.getResponse();
            // 设置信息给客户端不解析
            String type = new MimetypesFileTypeMap().getContentType(fileName);
            if (response != null) {
                // 设置content-type,即告诉客户端所发送的数据属于什么类型
                response.setHeader("Content-type", type);
                // 设置编码
                String code = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
                // 设置扩展头,当Content-Type 的类型为要下载的类型时 , 这个信息头会告诉浏览器这个文件的名字和类型。
                response.setHeader("Content-Disposition", "attachment;filename=" + code);
                FileUtil.download(fileName, response);
            }
        }
    }

controller层代码:

@GetMapping("/downTemplate")
    public String downTemplate(@RequestParam("fileName") String fileName){
        try {
            studentService.downTemplate(fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

工具包:

public class FileUtil {

    public static void download(String fileName, HttpServletResponse response) throws IOException {
        // 发送给客户端的数据
        OutputStream outputStream = response.getOutputStream();
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        // 读取fileName
        bis = new BufferedInputStream(new FileInputStream(new File("./file/" + fileName)));
        int i = bis.read(buff);
        while (i != -1) {
            outputStream.write(buff, 0, buff.length);
            outputStream.flush();
            i = bis.read(buff);
        }
    }
}

模板存储位置

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值