HelloMonster
HelloMonster

Reputation: 39

Unzip the file using JSzip and convert file to ArrayBuffer

In the website, the user can upload a zip that contains one image and xml file. After upload the zip, the website will unzip the file and convert these file into ArrayBuffer. However, after the unzip, it gives me the object instead of file, and the fileReader can not work because of it.

Can anyone help me on this? The following is my code:

var zip = new JSZip();
zip.loadAsync(file.raw, {base64: true}).then(function(content) {
    var img = Object.entries(data.files).filter(([fileName]) =>
       fileName.endsWith('.png'),
    );
    var xml = Object.entries(data.files).filter(([fileName]) =>
       fileName.endsWith('.xml'),
    );
    var reader = new FileReader();
    reader.readAsArrayBuffer(img[0][1]);
    reader.onload = function(e){
       console.log(this.result)  
    }

});

I also tried console.log(img) and console.log(content), but the output is not expected.

console.log(img);
console.log(content);
// img Output:
(2) [Array(2), Array(2)]
0: (2) ["sample.png", i]
1: (2) ["__MACOSX/._sample.png", i]
length: 2
__proto__: Array(0)

// content Output:
i {files: {…}, comment: null, root: "", clone: ƒ}
clone: ƒ ()
comment: null
files:
sample.png: i {name: "sample.png", dir: false, date: Fri Jun 19 2020 01:04:54 GMT+0800 (中国标准时间), comment: null, unixPermissions: 33188, …}
sample.xml: i {name: "sample.xml", dir: false, date: Wed Jul 01 2020 21:56:20 GMT+0800 (中国标准时间), comment: null, unixPermissions: 33188, …}
__MACOSX/._sample.png: i {name: "__MACOSX/._sample.png", dir: false, date: Fri Jun 19 2020 01:04:54 GMT+0800 (中国标准时间), comment: null, unixPermissions: 33188, …}
__MACOSX/._sample.xml: i {name: "__MACOSX/._sample.xml", dir: false, date: Wed Jul 01 2020 21:56:20 GMT+0800 (中国标准时间), comment: null, unixPermissions: 33188, …}
__proto__: Object
root: ""
__proto__: Object

Upvotes: 0

Views: 2129

Answers (1)

HelloMonster
HelloMonster

Reputation: 39

Resolved the issue by following code:

zip.file(img[0][0]).async("arraybuffer")
.then(function(ArrayBuffer){
       console.log("Image ArrayBuffer: ");
        console.log(ArrayBuffer);
});

Upvotes: 1

Related Questions