Extracting zipped files using JSZIP in javascript

后端 未结 3 1394
南笙
南笙 2021-02-04 13:21

In my webpage, a user is supposed to upload a zipped file. Within the zipped file are 2 files: another zip file and a txt file. On my server, after receiving the zip, I want to

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-04 14:05

    This answer is cordova-plugin-file specific.

    As stated in the docs:

    Directory entries have to be created successively. For example, the call fs.root.getDirectory('dir1/dir2', {create:true}, successCallback, errorCallback) will fail if dir1 did not exist.

    I am almost certain that the currently accepted answer cannot guarantee that file content/folders are always retrieved in the same order. This could result in problems with an API such as cordova-plugin-file. Especially when you invoke another async function to asynchronously create the directory on the filesystem.

    You may want to filter the directories of your zip archive first and create them in a sync manner before continuing to extract other files as already answered:

    const directoryNames = Object.keys(zip.files).filter(name => zip.files[name].dir);
    for (const directoryName of directoryNames) {
        await this.createDirectory(directoryName, dirEntry);
    }
    // ...
    
    private createDirectory = (dirName: string, dirEntry: DirectoryEntry) => {
        const promise = new Promise(resolve, reject) => {
            dirEntry.getDirectory(dirName, { create: true }, dirEntry => {
                resolve(dirEntry);
            }, fileError => reject(fileError));
        });
        return promise;
    }
    

提交回复
热议问题