您现在的位置是:首页 > 经典句子

js 前端下载文件并压缩保存到本地

作者:纳雷武时间:2024-04-13 08:36:45分类:经典句子

简介  文章浏览阅读841次。前端下载图片并打包压缩保存到本地_jszip下载zip文件到本地

点击全文阅读

第一步下载包

npm i jszip save-as-file -S

第二步引入包

import JSZip from "jszip";import saveFile from "save-as-file";

第三步使用

const zip = new JSZip();const cache = {};const promises = [];batchDownLoadZip(  [    "http://xxx.jpg",    "http://xxx.png",  ],  "压缩文件名称");function batchDownLoadZip(fileList, zipName) {  return new Promise((resolve, reject) => {    fileList.forEach((item, index) => {      // item.fileUrl.split('?')[0] 处理fileList里的url地址 去除?号和后面的字符串      const promise = getImgArrayBuffer(item.split("?")[0])        .then((data) => {          // 下载文件, 并存成ArrayBuffer对象          // item.fileName fileList里的文件名          zip.file(index + ".png", data, { binary: true }); // 逐个添加文件          cache[item.fileName] = data; // 可要可不要 用来打印查检查添加了那些文件        })        .catch((e) => {          console.log("文件访问失败");        });      promises.push(promise); // 加到promises队列里    });    Promise.all(promises)      .then(() => {        // 异步队列全部完成时 执行下面代码        console.log("开始压缩");        zip          .generateAsync({ type: "blob" })          .then((content) => {            // 生成二进制流            console.log("压缩成功", content);            saveFile(content, zipName);            console.log("文件保存成功");            resolve();          })          .catch((e) => {            console.log("下载失败");            reject(e);          });      })      .catch((e) => {        console.log("压缩失败");        reject(e);      });  });}function getImgArrayBuffer(href) {  return new Promise((resolve, reject) => {    // 通过请求获取文件blob格式    const xmlhttp = new XMLHttpRequest();    xmlhttp.open("GET", href, true);    xmlhttp.responseType = "blob";    xmlhttp.onload = function() {      if (this.status === 200) {        resolve(this.response);      } else {        reject(this.status);      }    };    xmlhttp.send();  });}        

点击全文阅读

郑重声明:

本站所有活动均为互联网所得,如有侵权请联系本站删除处理

我来说两句