[vue] jszip html-docx-js file-saver 图片,纯文本 ,打包压缩,下载跨域问题

npm install jszip file-saver
import JSZip from 'jszip';
import FileSaver from 'file-saver';

JSZip

创建JSZip实例:

const zip = new JSZip();

创建文件:支持导出纯文本

zip.file("hello.txt", "Hello World\n");

创建文件夹:

zip.folder("file")

只压缩有地址的文件

// 举个栗子

const dataList = [
    {
        fileUrl: 'https://www.xxx.com/data/data_service/20210429/144b4b1e4e457485c10fed54b8bc8d48.docx',
        fileName: '文件一'
    },
    {
        fileUrl: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
        fileName: '图片1'
    },
    {
        fileUrl: 'https://......docx',
        fileName: '文件二'
    },
    {
        fileUrl: 'https://......txt',
        fileName: '文件三'
    },
    {
        fileUrl: 'https://......jpg',
        fileName: '文件四'
    },
];
// 下载全部附件-压缩包
downloadBtn() {
  const blogTitle = '全部附件'; // 下载后压缩包的名称
  const zip = new JSZip();
  const promises = [];

  // 处理 docx/image
  this.dataList.forEach((item) => {
    const promise = this.getBlob(item.fileUrl).then((data) => {
      // 下载文件, 并存成ArrayBuffer对象(blob)
      zip.file(item.fileName, data, { binary: true }); // 逐个添加文件
    });
    promises.push(promise);
  });

  Promise.all(promises).then(() => {
    // 生成二进制流
    zip.generateAsync({ type: 'blob' }).then((blob) => {
      FileSaver.saveAs(blob, blogTitle); // 利用file-saver保存文件  blogTitle:自定义文件名
    });
  }).catch((res) => {
    this.$message.error('文件压缩失败');
  });
},
// 文件以流的形式获取(参数url为文件链接地址)
getBlob(url) {
  return new Promise((resolve) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = () => {
      if (xhr.status === 200) {
        resolve(xhr.response);
      }
    };
    xhr.send();
  });
},

导出纯文本+图片

先使用html-docx-js库将HTML内容转换为Word文档

npm install html-docx-js
import htmlDocx from 'html-docx-js/dist/html-docx';
// 下载全部附件-压缩包
downloadBtn() {
  const blogTitle = '全部附件'; // 下载后压缩包的名称
  const zip = new JSZip();
  const promises = [];
  const htmlContent = `<span style="font-family:宋体; font-size:12pt">报告时间</span>`
  // 处理 Html文本
  if (htmlContent ) {
    const name = "11.docx";
    const blob = htmlDocx.asBlob(htmlContent);
    zip.file(name, blob, { binary: true }); // 创建文件
  }

  zip.file("Hello.txt", "Hello World\n"); // 支持纯文本等

   // 处理 docx/image
  this.dataList.forEach((item) => {
    const promise = this.getBlob(item.fileUrl).then((data) => {
      // 下载文件, 并存成ArrayBuffer对象(blob)
      zip.file(item.fileName, data, { binary: true }); // 逐个添加文件
    });
    promises.push(promise);
  });

  Promise.all(promises).then(() => {
    // 生成二进制流
    zip.generateAsync({ type: 'blob' }).then((blob) => {
      FileSaver.saveAs(blob, blogTitle); // 利用file-saver保存文件  blogTitle:自定义文件名
    });
  }).catch((res) => {
    this.$message.error('文件压缩失败');
  });
},

跨域:

点击下载后浏览器会报跨域问题,这个问题并非前端问题,需要后端在存储文件的服务器中设置允许跨域,添加 Access-Control-Allow-Origin 即可!

在这里插入图片描述

在这里插入图片描述


参考:

JS实现单个或多个文件批量下载的方法详解

前端批量获取文件并打包压缩解决方案

vue中实现文件批量打包压缩下载(以及下载跨域问题分析)

Vue.js 2.x 中,你可以使用一些库来实现读取本地 Word 文件并提供下载功能。其中一个常用的库是 "file-saver" 和 "js-file-explorer" 或 "html2canvas" 结合 "docxtemplater" 来处理 Word 文档。以下是一个简单的步骤: 1. 首先,你需要安装必要的依赖: ```bash npm install file-saver js-file-explorer html2canvas docxtemplater ``` 2.Vue 组件中,你可以通过浏览器的 File API 选择文件: ```html <input type="file" @change="handleFileSelect($event)" /> ``` 3. 使用 `handleFileSelect` 函数来处理文件选择: ```javascript methods: { handleFileSelect(e) { const file = e.target.files[0]; if (file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') { this.readFile(file); } else { alert('请选择 Word 文件'); } }, readFile(file) { // 使用 FileReader 对象读取文件内容 const reader = new FileReader(); reader.onload = (e) => { this.wordContent = e.target.result; // 将 Word 内容存储在组件变量中 this.downloadWord(); // 调用下载函数 }; reader.readAsArrayBuffer(file); }, }, ``` 4. 创建下载 Word 的方法: ```javascript downloadWord() { let doc = new Docxtemplater(this.wordContent); // 替换模板中的数据,这里假设你有一个数据对象 data doc.render({ data }); const blob = new Blob([doc.getZip().generateNodePacket()], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'}); saveAs(blob, 'output.docx'); // 使用 saveAs 函数保存为 Word 文件 }, ``` 请注意,这只是一个基础示例,实际应用中可能还需要考虑错误处理、访问等问题,并确保满足用户的隐私和安全需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值