• SpringBoot 下载 docx 文档


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

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

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

    一、具体代码

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

    1. <dependency>
    2. <groupId>org.apache.poi</groupId>
    3. <artifactId>poi-scratchpad</artifactId>
    4. <version>5.2.2</version>
    5. </dependency>
    6. <dependency>
    7. <groupId>org.apache.poi</groupId>
    8. <artifactId>poi-ooxml</artifactId>
    9. <version>5.2.2</version>
    10. </dependency>

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

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

    1. public void downloadDoc(HttpServletResponse response) throws UnsupportedEncodingException {
    2. String baseUrl = "D:\\testDownload\\";
    3. String temp = "5939.docx";
    4. File file = new File(baseUrl + temp);
    5. //获取文件名
    6. String filename = file.getName();
    7. //获取后缀名
    8. int i = filename.lastIndexOf(".");
    9. String extension = filename.substring(i+1);
    10. //设置响应的信息
    11. response.reset();
    12. response.setCharacterEncoding("UTF-8");
    13. response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf8"));
    14. response.setHeader("Pragma", "no-cache");
    15. response.setHeader("Cache-Control", "no-cache");
    16. //设置浏览器接受类型为流
    17. response.setContentType("application/octet-stream;charset=UTF-8");
    18. try {
    19. InputStream in = new FileInputStream(file);
    20. // 将文件写入输入流
    21. OutputStream out = response.getOutputStream();
    22. if("docx".equals(extension) || "doc".equals(extension)) {
    23. //docx文件就以XWPFDocument创建
    24. XWPFDocument docx = new XWPFDocument(in);
    25. docx.write(out);
    26. docx.close();
    27. } else {
    28. //其他类型的文件,按照普通文件传输 如(zip、rar等压缩包)
    29. int len;
    30. //一次传输1M大小字节
    31. byte[] bytes = new byte[1024];
    32. while ((len = in.read(bytes)) != -1) {
    33. out.write(bytes , 0 , len);
    34. }
    35. }
    36. } catch (Exception e) {
    37. e.printStackTrace();
    38. }
    39. }

    二、前端如何下载

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

  • 相关阅读:
    【虚幻引擎】实现类LOL缓慢扣血血条
    使用 vue-element-admin 开发后台管理系统【安装】
    正确重写equals和hashcode方法
    【UE】抓取物体
    crmebpro2.2.2多店版,可包更新
    AD9361手册解读
    PROB: Probabilistic Objectness for Open World Object Detection(论文解析)
    SpringBoot接入GrayLog(分布式日志组件)
    java计算机毕业设计火车订票管理系统源码+mysql数据库+系统+lw文档+部署
    Spring boot集成nacos图文教程
  • 原文地址:https://blog.csdn.net/tengyuxin/article/details/127880342