博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

解决前端JSZip读取压缩包内文件中文名称乱码问题

Posted on 2024-02-01 10:59  Hhuizi  阅读(59)  评论(0编辑  收藏  举报
 1 import JSZip from "jszip";
 2 
 3 function jszipFile(file) {
 4   if (!/\.zip$/i.test(file.name)) {
 5     reject(`文件"${file.name}"不是zip文件`);
 6     return;
 7   }
 8 
 9   const fileReader = new FileReader();
10 
11   // 转换文件为ArrayBuffer
12   fileReader.readAsArrayBuffer(file);
13 
14   const decoder = new TextDecoder("gbk");
15 
16   // 监听完成事件
17   fileReader.onload = function fn() {
18     const zipper = new JSZip();
19     zipper
20       .loadAsync(fileReader.result, {
21         decodeFileName: (bytes) => {
22           return decoder.decode(bytes);
23         }
24       })
25       .then((zip) => {
26         console.log(zip.files);
27       });
28   };
29 }