使用JSZip解压文件夹失败:提示压缩包损坏或签名异常
Let's break down why you're hitting this issue and walk through simple fixes to get JSZip working with your folder-based zip files.
First, let's recap your setup to make sure we're on the same page:
- You generated two zips on Ubuntu:
text.zip(single text file) andfolder.zip(a folder containing text files) - You're serving these zips locally via
serve text.zipunzips perfectly with JSZip, butfolder.zipthrows the signature mismatch error- Adm-Zip handles both zips without issues, so the zip files themselves aren't corrupted
What's Causing the Error?
The error message points to an unexpected signature (\x00\x50\x4B\x07 instead of the expected \x50\x4B\x03\x04). This almost always happens when the binary zip data isn't being handled correctly during download or conversion to a format JSZip can process.
Your original code uses Buffer.from(response.data, 'binary') to convert the Blob response to a buffer—but forcing a 'binary' encoding on a Blob can mangle the raw byte data, especially for folder zips which have more complex internal structures than single-file zips.
Solution 1: Switch to responseType: 'arraybuffer'
JSZip works seamlessly with ArrayBuffers, which preserve raw binary data without encoding mismatches. Let's adjust your axios request:
import axios from 'axios'; import * as JSZip from 'jszip'; axios.get( "http://localhost:5000/folder.zip", { responseType: "arraybuffer" } // Swap 'blob' for 'arraybuffer' ) .then((response) => { const zip = new JSZip(); return zip.loadAsync(response.data) .then((zipContent) => { console.log('JSZip unzipped successfully!'); zipContent.forEach((path, file) => { console.log(path); }); }); }) .catch((e) => { console.log(`Error: ${e}`); });
Solution 2: Properly Convert Blob to Buffer (If You Need to Keep blob as Response Type)
If you have to stick with blob as the response type, convert it to an ArrayBuffer properly using the Blob's built-in arrayBuffer() method instead of forcing a binary encoding:
import axios from 'axios'; import * as JSZip from 'jszip'; axios.get( "http://localhost:5000/folder.zip", { responseType: "blob" } ) .then(async (response) => { const arrayBuffer = await response.data.arrayBuffer(); const zip = new JSZip(); return zip.loadAsync(arrayBuffer) .then((zipContent) => { console.log('JSZip unzipped successfully!'); zipContent.forEach((path, file) => { console.log(path); }); }); }) .catch((e) => { console.log(`Error: ${e}`); });
Quick Sanity Check: Verify Your Zip Generation
Just to rule out any issues with how you're creating the zip on Ubuntu, make sure you're using the standard zip command with the recursive flag:
zip -r folder.zip your-target-folder/
Avoid any non-standard compression flags that might create zips with headers JSZip doesn't support.
内容的提问来源于stack exchange,提问作者lhk

