`FileReader.readAsBinaryString()` **非標準方法**,僅 Firefox/Chrome 早期實現。IE 全系列、Edge (Legacy)、Safari 早期版本**均不支持**。標準替代方案是 `readAsArrayBuffer()` + `Uint8Array` 處理二進制數據。
function readFileAsBinaryString(file, callback) {
const reader = new FileReader();
reader.onload = function(e) {
const arrayBuffer = e.target.result;
const bytes = new Uint8Array(arrayBuffer);
// 轉為二進制字符串(每字節一字符,code point 0-255)
let binaryStr = '';
for (let i = 0; i < bytes.length; i++) {
binaryStr += String.fromCharCode(bytes[i]);
}
callback(binaryStr);
};
reader.readAsArrayBuffer(file); // 標準方法,全瀏覽器支持
}
if (!FileReader.prototype.readAsBinaryString) {
FileReader.prototype.readAsBinaryString = function(file) {
const self = this;
const reader = new FileReader();
reader.onload = function(e) {
const arr = new Uint8Array(e.target.result);
let binary = '';
for (let i = 0; i < arr.length; i++) binary += String.fromCharCode(arr[i]);
// 模擬原生事件
const event = new Event('load');
event.target = { result: binary };
self.onload?.(event);
};
reader.readAsArrayBuffer(file);
};
}
你貼的代碼:
<meta http-equiv="X-UA-Compatible" content="IE=edge,Chrome=1" />
<meta http-equiv="X-UA-Compatible" content="IE=8" />
**無效原因**:
**正確寫法**(放在 `
` 首位):<meta http-equiv="X-UA-Compatible" content="IE=edge" />
含義:強制 IE 使用**當前安裝版本的最高標準模式**(IE11 即 Edge 模式),而非兼容模式。
| 需求 | 現代標準方案 | IE9+ 支持 | IE8- 支持 |
|---|---|---|---|
| 讀取文件文本 | `readAsText(file, 'utf-8')` | ✅ | ✅ |
| 讀取文件二進制 | `readAsArrayBuffer()` + `Uint8Array` | ✅ | ❌ (無 FileReader) |
| 上傳文件 | `FormData` + `fetch`/`XMLHttpRequest` | ✅ | ❌ (需 FormData Polyfill 或 Flash) |
| 拖拽上傳 | Drag & Drop API | ✅ | ❌ |
<!--[if lte IE 11]>
<script src="polyfill.min.js"></script>
<![endif]-->
IE 不支持 `readAsBinaryString` 是**標準化進程的必然結果**。請直接使用 **`readAsArrayBuffer()` + `Uint8Array`** 處理二進制文件,配合 `core-js` Polyfill 覆蓋 IE9-11,徹底拋棄非標準 API 與失效的 `X-UA-Compatible` 臭蟲配置。現代 Web 開發,**擁抱標準、優雅降級、條件編譯** 是正道。