如何在服务器端(Google Apps Script)检测Blob或字符串的字符编码?
在Google Apps Script服务器端检测Blob或字符串的字符编码
可以在Google Apps Script(GAS)服务器端实现Blob或字符串的字符编码检测,核心思路是通过分析字节特征(如BOM)或尝试用不同编码解码验证来判断。
检测Blob的编码
Blob可直接获取原始字节数组,通过检查字节头的BOM标识,或尝试用常见编码解码来确定:
function detectBlobEncoding(blob) { const bytes = blob.getBytes(); // 检查字节顺序标记(BOM) if (bytes.length >= 3 && bytes[0] === 0xEF && bytes[1] === 0xBB && bytes[2] === 0xBF) { return 'UTF-8 (带BOM)'; } if (bytes.length >= 2) { if (bytes[0] === 0xFF && bytes[1] === 0xFE) { return 'UTF-16LE'; } if (bytes[0] === 0xFE && bytes[1] === 0xFF) { return 'UTF-16BE'; } } // 尝试用常见编码解码,验证合法性 const testEncodings = ['UTF-8', 'GBK', 'Shift-JIS']; for (const enc of testEncodings) { try { Utilities.newBlob(bytes).getDataAsString(enc); return enc; } catch (e) { // 解码失败,跳过当前编码 continue; } } return '无法识别的编码'; }
检测字符串的编码
GAS中的字符串默认以UTF-16存储,若要判断字符串对应的原始编码,需通过反向生成字节并验证的方式(注意:这种方法只能判断字符串是否可被某编码表示,无法100%确定原始编码):
function detectStringEncoding(targetStr) { const candidateEncodings = ['UTF-8', 'GBK', 'Shift-JIS', 'UTF-16LE', 'UTF-16BE']; for (const enc of candidateEncodings) { try { // 将字符串按指定编码转为Blob,再解码回字符串 const tempBlob = Utilities.newBlob(targetStr, enc); const decodedStr = tempBlob.getDataAsString(enc); if (decodedStr === targetStr) { return enc; } } catch (e) { continue; } } return '无法识别的编码'; }
注意事项
- 编码检测是启发式方法,对于无BOM的单字节编码(如GBK与Shift-JIS)可能存在误判,需结合业务场景调整候选编码顺序。
- GAS的
Utilities.newBlob()支持的编码范围有限,优先选择常见编码进行测试。 - 若字符串来自外部文件,建议直接处理原始Blob而非已转换的字符串,这样检测结果更准确。
内容的提问来源于stack exchange,提问作者Ryu Hiroyama
相关产品推荐
相关产品推荐

