Skip to content

FileReader readAsText 编码错误

快速摘要

你对非 UTF-8 文件调用 readAsText 却未指定编码——结果出现乱码字符。

为什么发生

  • 文件用 GBK、Shift-JIS 或 Latin-/1 编码却以 UTF-8 读取

  • 未向 readAsText 传入编码参数

  • BOM 被读取器去掉或误判

最小示例

✗ 错误代码
const reader = new FileReader();
reader.onload = e => console.log(e.target.result); // garbled for GBK file
reader.readAsText(gbkFile); // defaults to UTF-8
✓ 修复代码
const reader = new FileReader();
reader.onload = e => console.log(e.target.result);
reader.readAsText(gbkFile, 'gbk'); // correct encoding

readAsText 默认 UTF-8,故 GBK 文件产生乱码。传入 'gbk' 作为第二个参数可正确解码字节。

如何诊断

  • 检查结果字符串是否含替换字符(U+FFFD)或乱码

  • 用十六进制编辑器或 file 命令检查文件编码

  • 尝试用显式编码参数读取

如何修复

  • 传入正确编码:reader.readAsText(file, 'gbk')

  • 用 TextDecoder 配合检测到的编码以获得更多控制

  • 可能时先把文件转为 UTF-8 再读取

如何预防

  • 始终以 UTF-8 存储与传输文本文件

  • 读取前检测编码(如用 jschardet)

相关资源

相关术语

相关课程

  • DOM

    学习 FileReader。

← 返回语言