You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JSZip generateAsync报错TypeError: e3.charCodeAt is not a function求助

解决JSZip导出压缩文件时的charCodeAt is not a function错误

问题根源

你调用ziptool.file()时,传入了Blob对象但设置了{binary: false}。JSZip在非binary模式下会将输入视为字符串,尝试执行字符串的charCodeAt方法做UTF-8编码,但Blob不是字符串类型,因此触发报错。

解决方案

方案1:直接传入字符串(最简洁)

JSON.stringify生成的字符串可直接交给JSZip处理,无需手动转Blob或Uint8Array,JSZip会自动完成编码:

import JSZip from 'jszip';
import FileSaver from 'file-saver';

const exportData = (evt: any) => {
  const reportFileName = 'myreport.zip';
  const ziptool = new JSZip();
  const blob_raw_data = { id: 'xxxxxxx', bm: 0, em: 1500 }; 
  const jsonse = JSON.stringify(blob_raw_data, null, '\t');
  // 直接传字符串,binary参数可省略(默认false,适配字符串)
  ziptool.file('values.txt', jsonse);
  ziptool.generateAsync({ type: "blob" })
    .then(function (blob_data) {
      FileSaver.saveAs(blob_data, reportFileName);
    });
};

方案2:传入二进制数据时设置binary: true

如果需要保留Blob/Uint8Array的处理逻辑,必须告诉JSZip这是二进制数据,避免字符串编码操作:

import JSZip from 'jszip';
import FileSaver from 'file-saver';

const exportData = (evt: any) => {
  const reportFileName = 'myreport.zip';
  const ziptool = new JSZip();
  const blob_raw_data = { id: 'xxxxxxx', bm: 0, em: 1500 }; 
  const jsonse = JSON.stringify(blob_raw_data, null, '\t');
  const bytes = new TextEncoder().encode(jsonse);
  const blob = new Blob([bytes], { type: "text/plain;charset=utf-8" });
  // 传入Blob时设置binary: true
  ziptool.file('values.txt', blob, {binary: true});
  ziptool.generateAsync({ type: "blob" })
    .then(function (blob_data) {
      FileSaver.saveAs(blob_data, reportFileName);
    });
};

也可以直接传入Uint8Array(效果一致):

// ... 其他代码不变
ziptool.file('values.txt', bytes, {binary: true});
// ...

补充说明

  • binary: false(默认):JSZip将输入视为UTF-8字符串,自动编码为二进制
  • binary: true:JSZip直接使用输入的二进制数据,不做字符串编码处理

内容的提问来源于stack exchange,提问作者For Comment

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 04:24:59