美文网首页
JSZip压缩与解压的基本使用

JSZip压缩与解压的基本使用

作者: 兮木兮木 | 来源:发表于2020-10-11 15:52 被阅读0次
//相关api介绍,具体可参考jszip源码中的注释
/**
 * 从文档中读取文件
 *
 * @param Path 要读取文件的相对路径
 * @return File matching path, null if no file found
 */
  JSZip.file(path: string): JSZip.JSZipObject | null;

/**
 *把读取的文件内容以哪中格式展示出来
 *OutputType: base64,
    string,
    text,
    binarystring,
    array,
    uint8array,
    arraybuffer,
    blob,
    nodebuffer,
    支持以上类型
    返回一个Promise对象,将结果给出来
 */
JSZipObject.async<T extends OutputType>(type: T, onUpdate?: OnUpdateCallback): Promise<OutputByType[T]>;

/**
     * 添加一个文件到文档中
     *
     * @param path 文件的相对路径
     * @param data 文件的内容
     * @param options Optional information about the file
     * @return JSZip object
     * 具体可参考下面的使用案例
     */
    JSZip.file<T extends JSZip.InputType>(path: string, data: InputByType[T] | Promise<InputByType[T]>, options?: JSZip.JSZipFileOptions): this;
    JSZip.file<T extends JSZip.InputType>(path: string, data: null, options?: JSZip.JSZipFileOptions & { dir: true }): this;
/**
 * 返回一个JSZip的实例,并且会在根目录新建一个文件夹
 *
 * @param name 文件夹的名字
 * @return New JSZip object with the given folder as root or null
 */
 folder(name: string): JSZip | null;

/**
 * 异步生成一个文档,返回一个Promise
 *
 * @param options Optional options for the generator
 * @param onUpdate The optional function called on each internal update with the metadata.
 * @return The serialized archive
 */
generateAsync<T extends JSZip.OutputType>(options?: JSZip.JSZipGeneratorOptions<T>, onUpdate?: OnUpdateCallback): Promise<OutputByType[T]>;

/**
 * 异步加载一个zip文件
 *
 * @param data Serialized zip file
 * data的类型可选:
 * interface InputByType {
    base64: string;
    string: string;
    text: string;
    binarystring: string;
    array: number[];
    uint8array: Uint8Array;
    arraybuffer: ArrayBuffer;
    blob: Blob;
    stream: NodeJS.ReadableStream;
    }
    type InputFileFormat = InputByType[keyof InputByType];
 *
 * @param options 反序列化的配置选项
 * @return Returns promise
 */
loadAsync(data: InputFileFormat, options?: JSZip.JSZipLoadOptions): Promise<JSZip>;


  • 压缩文件

    需用到jszip,file-saver 两个库,可参考以下案例以及上方的api介绍

    //官方案例
    var zip = new JSZip();
     
    zip.file("Hello.txt", "Hello World\n");
     
    var img = zip.folder("images");
    img.file("smile.gif", imgData, {base64: true});
     
    zip.generateAsync({type:"blob"}).then(function(content) {
        // see FileSaver.js
        saveAs(content, "example.zip");
    });
    
  • 解压文件

              let zip = new JSZip();
          var xhr = new XMLHttpRequest();
          xhr.open('GET', 'http://localhost:8000/book.zip', true);
          xhr.responseType = 'blob';
          xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200 || xhr.status === 304) {
    
              zip.loadAsync(xhr.response, {optimizedBinaryString: true}).then(res => {
                //res.files里包含整个zip里的文件描述、目录描述列表
                //res本身就是JSZip的实例
                for (let key in res.files) {
                  //判断是否是目录
                  if (!res.files[key].dir) {
                    //找到我们压缩包所需要的json文件
                    if (/\.(json)$/.test(res.files[key].name)) {
                      res.file(res.files[key].name).async('string')
                        .then(content => {
                          //得到我们需要的JSON文件内容
                          console.log(JSON.parse(content))
                          })
                    }
                  }
                }          
              }).catch(err => {
                console.log(err)
              });          
            }
          };
          xhr.send();
    

相关文章

网友评论

      本文标题:JSZip压缩与解压的基本使用

      本文链接:https://www.haomeiwen.com/subject/geyepktx.html