1.0.1 • Published 1 year ago

web-async-zip v1.0.1

Weekly downloads
-
License
ISC
Repository
-
Last release
1 year ago

web-async-zip

介绍

前端异步打包下载

软件架构

封装 StreamSaver.js ZipStream.js

安装

npm i web-async-zip

使用

import {StreamSaver,ZIP} from "web-async-zip";

/**
 * 
 * @param { [{name:String,dir:String,url:String}] } files 
 * @param {String} zipName 
 * @returns 
 */
export function downloadBlobZip(files, zipName = '未命名.zip') {
  let arr = files.map(i => {
    return urlToBlob(i).then(f => {
      return {
        name: (f.dir ? `${f.dir}/` : "") + f.name,
        stream: () => f.blob.stream()
      };
    });
  });

  const fileStream = StreamSaver.createWriteStream(zipName)

  const readableZipStream = new ZIP({
    start(ctrl) {
      arr.forEach(item => item.then(opt => ctrl.enqueue(opt)));

      Promise.all(arr).then(() => ctrl.close()).catch(() => ctrl.close());
    }
  })

  // more optimized
  if (window.WritableStream && readableZipStream.pipeTo) {
    return readableZipStream.pipeTo(fileStream).then(() => console.log('done writing'))
  } else {
    // less optimized
    const writer = fileStream.getWriter()
    const reader = readableZipStream.getReader()
    const pump = () => reader.read()
      .then(res => res.done ? writer.close() : writer.write(res.value).then(pump))

    pump()
  }
}

注:urlToBlob 方法需要自己实现,即请求url获取blob逻辑。

1.0.1

1 year ago

1.0.0

1 year ago