Angular 学习笔记 work with zip (压缩文件格式)

最近在做批量创建. 

上回说到了 读写 excel, 那么就可以通过 excel 的资料来创建资料了。但是资料经常会有图片,而 excel 里面放图片有点不太好.

于是就想 upload excel 的同时在附带另一个 folder 里面装图片, excel 就写对应的图片名字就好了. 

那一个 table 可能有好几个 column 都是图片, 如果把图片一股脑丢 input file 体验不太好. 所以最好是分几个 folder 装图片对应 column 

然后 zip 起来丢 input file. 虽然 input file 是可以支持丢 folder 的, 但是 safari 好像是不支持的. 

所以还是用 zip 比较妥当. windows 10 都自带 zip 对用户来说不算太难. 

那么来说说 js 如果读写 zip file.

 

nodejs 发展多年,你说没有 plug in 做这个事没有人会相信. 所以随便找一下就有了. 

https://github.com/Stuk/jszip

有 .d.ts 所以对 ng 很友好.

跟着做就可以了

https://stuk.github.io/jszip/documentation/examples/read-local-file-api.html

太简单这里就不叙述了.

上面只是读,写的部分目前没有需求所以我也没有测试. 以后要才看呗

 

记入一下基础的东西.

ArrayBuffer, Blob 我经常搞混. 可以看这篇

https://www.gobeta.net/books/ruanyf-javascript-tutorial/bom/arraybuffer/

ArrayBuffer 有点像 c# 的 memory stream 

blob 像 file stream 

平时 input file 的 File 对象,是 blob 的一个衍生来的.

所以通常我们会用到的是 blob

大概懂就好啦. 够用

 

记入一下测试的代码

import * as JSZip from 'jszip';

const input = document.getElementById('input') as HTMLInputElement;
input.addEventListener('input', async e => {
    const file = Array.from(input.files)[0];
    // const arrayBuffer = await raedFileAsync(file);
    const zip = await JSZip.loadAsync(file);
    console.log(zip);
    type PathAndZipEntry = {
        relativePath: string;
        file: JSZip.JSZipObject;
    }
    const pathAndZipEntries: PathAndZipEntry[] = [];
    zip.forEach((relativePath, file) => {
        pathAndZipEntries.push({ relativePath, file });
    });
    const ajaxAsync = async (blob: Blob, fileName: string): Promise<any> => {
        return new Promise(resolve => {
            const formData = new FormData();
            formData.append('file', blob, fileName);
            const xhr = new XMLHttpRequest();
            xhr.open('POST', 'http://192.168.1.152:61547/api/uploadFile');
            xhr.onload = () => {
                resolve(xhr.response);
            }
            xhr.send(formData);
        });
    }

    for await (const { relativePath, file } of pathAndZipEntries) {
        console.log('relativePath', relativePath);
        const paths = relativePath.split('/');
        const blob = await file.async('blob');
        console.log(await ajaxAsync(blob, paths[paths.length - 1]));
    }

    input.value = '';
});

 

posted @ 2020-05-23 21:40  兴杰  阅读(678)  评论(0编辑  收藏  举报