前端压缩文件、下载

使用插件:file-saver、jszip

安装插件:

1
2
npm install file-saver --save
npm install jszip --save

  压缩文件(压缩的内容需要是blob流,可以是后端接口返回的blob流,如果是远程文件地址,可以参看第3条)

1、一个文件压缩:

1
2
3
4
5
6
7
8
9
import saveAs from 'file-saver';
import JSZip  from 'jszip';
 
// 在函数体中调用
const zip = new JSZip();
zip.file(filename, blob);
zip.generateAsync({type:'blob'}).then(function(content) {
    saveAs(content, '压缩包名称.zip');
});

  

2、多个文件压缩

1
2
3
4
5
6
7
8
9
10
11
12
import saveAs from 'file-saver';
import JSZip  from 'jszip';
 
// 在函数体中调用以下,list里面存放数据
const zip = new JSZip();
const list = [];
list.forEach((item) => {
    zip.file(item.fileName, item.blob);
 });
zip.generateAsync({type:'blob'}).then(function(content) {
    saveAs(content, '压缩包名称.zip');
});

 

3、如果文件地址是远程地址,需要先处理成blob流,再进行压缩处理

  • 远程文件地址转成blob流
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 远程文件地址转成blob/base64流
function getBase64ByURL (fileurl, data = {}) {
  return new Promise((resolve, reject) => {
    window.URL = window.URL || window.webkitURL;
    var xhr = new XMLHttpRequest();
    xhr.open('get', fileurl, true);
    xhr.responseType = 'blob';
    xhr.onload = function () {
      if (this.status == 200) {
        var blob = this.response;
        let oFileReader = new FileReader();
        oFileReader.onloadend = function (e) {
          resolve({blob,base64:e.target.result, ...data});
        };
        oFileReader.onerror = function(e){
          reject(e);
        };
        oFileReader.readAsDataURL(blob);
      }
    };
    xhr.send();
  });
}

  

  • 压缩下载文件
1
2
3
4
5
6
7
8
9
function jszipFile(list) {
  const zip = new JSZip();
  list.forEach((item) => {
    zip.file(item.fileName, item.blob);
  });
  zip.generateAsync({type:'blob'}).then(function(content) {
    saveAs(content, '压缩包名称.zip');
  });
}

  

  • 远程文件地址批量转换成流文件,再进行压缩、下载
1
2
3
4
5
6
7
8
9
10
11
import saveAs from 'file-saver';
import JSZip  from 'jszip';
// 在函数体中调用以下
const list = [];
list.forEach((item) => {
    const file = getBase64ByURL(item.fileUrl, item);
    arr.push(file);
});
Promise.all(arr).then((list) => {
    jszipFile(list || []);
});

  

有不足之处请指出,欢迎交流!

  

posted @   猕猴桃姑娘  阅读(213)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示