1、獲取文件二進制數據,這里只做示例,例如element-ui中文件上傳的beforeUpload方法,返回的file對象,然后使用FileReader對其進行轉換,再進行后續判斷?
function beforeUpload(file: File) { const reader = new FileReader();reader.readAsArrayBuffer(file);reader.onload = function (e: any) {// 等待file文件對象轉換完成}
}
2、將二進制數據處理為無符號整數,也就是處理為字節
reader.onload = function (e: any) {const btyes= new Uint8Array(e.target.result)console.log(btyes);if (isUTF8(btyes)) {console.log('utf-8');} else {console.log('GBK');}
}
3、isUTF8函數
// 判斷文件編碼格式的函數
function isUTF8(bytes) {var i = 0;while (i < bytes.length) {if ((// ASCIIbytes[i] == 0x09 ||bytes[i] == 0x0A ||bytes[i] == 0x0D ||(0x20 <= bytes[i] && bytes[i] <= 0x7E))) {i += 1;continue;}if ((// non-overlong 2-byte(0xC2 <= bytes[i] && bytes[i] <= 0xDF) &&(0x80 <= bytes[i + 1] && bytes[i + 1] <= 0xBF))) {i += 2;continue;}if ((// excluding overlongsbytes[i] == 0xE0 &&(0xA0 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) &&(0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF)) ||(// straight 3-byte((0xE1 <= bytes[i] && bytes[i] <= 0xEC) ||bytes[i] == 0xEE ||bytes[i] == 0xEF) &&(0x80 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) &&(0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF)) ||(// excluding surrogatesbytes[i] == 0xED &&(0x80 <= bytes[i + 1] && bytes[i + 1] <= 0x9F) &&(0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF))) {i += 3;continue;}if ((// planes 1-3bytes[i] == 0xF0 &&(0x90 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) &&(0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) &&(0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF)) ||(// planes 4-15(0xF1 <= bytes[i] && bytes[i] <= 0xF3) &&(0x80 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) &&(0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) &&(0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF)) ||(// plane 16bytes[i] == 0xF4 &&(0x80 <= bytes[i + 1] && bytes[i + 1] <= 0x8F) &&(0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) &&(0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF))) {i += 4;continue;}return false;}return true;
}