zoukankan      html  css  js  c++  java
  • vue将文件/图片批量打包下载zip

    TOC

    vue将文件/图片批量打包下载

    各种格式都可以,只要url能够打开或者下载文件即可.

    1.通过文件的url,使用js的XMLHttpRequest获取blob
    2.将blob压缩为zip

    由于异步并行加载文件,速度还是蛮快的,我141个4M多的图片,1分左右加载完成,49个4M的图片4秒

    • 添加依赖
    //npm install jszip
    //npm install file-saver
    在页面的script中引入依赖
    import JSZip from 'jszip'
    import FileSaver from 'file-saver'
    • 代码
          /**文件打包
           * arrImages:文件list:[{fileUrl:文件url,renameFileName:文件名}]
           * filename 压缩包名
           * */
          filesToRar(arrImages, filename) {
            let _this = this;
            let zip = new JSZip();
            let cache = {};
            let promises = [];
            _this.title = '正在加载压缩文件';
    
            for (let item of arrImages) {
              const promise= _this.getImgArrayBuffer(item.fileUrl).then(data => {
                // 下载文件, 并存成ArrayBuffer对象(blob)
                zip.file(item.renameFileName, data, { binary: true }); // 逐个添加文件
                cache[item.renameFileName] = data;
              });
              promises.push(promise);
            }
    
            Promise.all(promises).then(() => {
              zip.generateAsync({ type: "blob" }).then(content => {
                _this.title = '正在压缩';
                // 生成二进制流
                FileSaver.saveAs(content, filename); // 利用file-saver保存文件  自定义文件名
                _this.title = '压缩完成';
              });
            }).catch(res=>{
              _this.$message.error('文件压缩失败');
            });
          },
        //获取文件blob
          getImgArrayBuffer(url){
            let _this=this;
            return new Promise((resolve, reject) => {
                //通过请求获取文件blob格式
              let xmlhttp = new XMLHttpRequest();
              xmlhttp.open("GET", url, true);
              xmlhttp.responseType = "blob";
              xmlhttp.onload = function () {
                if (this.status == 200) {
                  resolve(this.response);
                }else{
                  reject(this.status);
                }
              }
              xmlhttp.send();
            });
    
          },




  • 相关阅读:
    Spring--AOP--面向切面编程
    Spring ---annotation (重点)--Resource, Component 重要!!!
    Spring ---annotation (重点)--AutoWired 不常用
    ts 交集类型
    ts 使用 keyof typeof
    Dart 编写Api弃用警告
    js 反应&行动
    perl 打印简单的help文档
    perl 在windows上获取当前桌面壁纸
    perl 打印目录结构
  • 原文地址:https://www.cnblogs.com/ziyue7575/p/5de6777a2c304e152b51c719c8d36c63.html
Copyright © 2011-2022 走看看