SpringBoot 下载 docx 文档

功能需求很简单:我想实现一个在线下载简历docx文档的功能

实现效果如下:点击下载后,就出现下载的文档

目前该方式有局限性只能下载微软的word文档,而wps的会下载失败

一、具体代码

使用的库为 org.apache.poi 专门处理Microsoft 的文档

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>5.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.2</version>
        </dependency>

实现思路:
(1)读取简历文件进入输入流 (输入流读取文件) 

(2)利用 XWPFDocument 装载 读取的数据流,将其写入 响应里面

 public void downloadDoc(HttpServletResponse response) throws UnsupportedEncodingException {
        String baseUrl = "D:\\testDownload\\";
        String temp = "5939.docx";
        File file = new File(baseUrl + temp);
        //获取文件名
        String filename  = file.getName();
        //获取后缀名
        int i = filename.lastIndexOf(".");
        String extension = filename.substring(i+1);

        //设置响应的信息
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" +  URLEncoder.encode(filename, "utf8"));
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        //设置浏览器接受类型为流
        response.setContentType("application/octet-stream;charset=UTF-8");
        try {
            InputStream in = new FileInputStream(file);
            // 将文件写入输入流
            OutputStream out = response.getOutputStream();
            if("docx".equals(extension) || "doc".equals(extension)) {
                //docx文件就以XWPFDocument创建
                XWPFDocument docx = new XWPFDocument(in);
                docx.write(out);
                docx.close();
            } else {
                //其他类型的文件,按照普通文件传输 如(zip、rar等压缩包)
                int len;
                //一次传输1M大小字节
                byte[] bytes = new byte[1024];
                while ((len = in.read(bytes)) != -1) {
                    out.write(bytes  , 0 , len);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

二、前端如何下载

我使用最简单的方式:window.open(ulr)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tengyuxin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值