React中使用jszip解压本地zip文件报错咨询
解决JSZip解压本地Zip文件报错问题
错误原因
你直接通过import导入Zip文件,得到的其实是文件的URL字符串,而非Zip文件的二进制数据。JSZip的loadAsync方法需要接收Blob、ArrayBuffer这类二进制内容,无法解析URL字符串,因此会抛出Can't find end of central directory : is this a zip file?错误。
正确解决方案
通过fetch请求public目录下的Zip文件,获取其二进制数据后再交给JSZip处理:
import JSZip from 'jszip'; function App() { const zip = new JSZip(); // 直接请求public目录下的文件(public下的文件会被部署到根路径) fetch('/test.zip') .then(response => { if (!response.ok) { throw new Error('请求Zip文件失败'); } // 将响应转为ArrayBuffer(或Blob,JSZip都支持) return response.arrayBuffer(); }) .then(buffer => zip.loadAsync(buffer)) .then(zipContent => { console.log('解压成功:', zipContent); // 可遍历解压后的文件,比如读取某个文件内容 // zipContent.file('目标文件名.txt').async('text').then(content => console.log(content)); }) .catch(error => { console.error('处理失败:', error); }); // render function return <div>JSZip测试</div>; } export default App;
补充说明
- public目录下的文件无需通过
import导入,直接使用根路径(/文件名)即可访问,React会将public目录下的文件原封不动打包到构建产物的根目录。 - 若不确定文件路径是否正确,可在浏览器开发者工具的Network面板查看请求是否成功。
内容的提问来源于stack exchange,提问作者timothyylim
相关产品推荐
相关产品推荐

