在 Google Chrome 中指定 Blob 编码 [英] Specifying blob encoding in Google Chrome
问题描述
以下代码(供应商标准化)运行良好,在 Firefox 8 中显示➀➁➂ Test",但在 Google Chrome 中显示➀âžâž‚ Test".除了使用文件系统 API 将文件写入临时文件系统之外,是否有任何方法可以在 Google Chrome 中保留 blob 的编码?
The following code (vendor normalized) works perfectly fine and displays "➀➁➂ Test" in Firefox 8, but displays "➀âžâž‚ Test" in Google Chrome. Is there any way to preserve encoding of blobs in Google Chrome short of writing a file to a temporary filesystem using the filesystem API?
var b = new Blob(["➀➁➂ Test"], {type: "text/plain;charset=UTF-8"});
var url = URL.createObjectURL(b);
open(url);
推荐答案
new Blob(["➀➁➂ Test"])
将生成一个表示该文本编码为 UTF-8 的 Blob.
new Blob(["➀➁➂ Test"])
will generate a Blob representing that text encoded as UTF-8.
浏览器假定文本文件应该在 ISO 中读取是一个奇怪的选择 IMM.
That browsers assumes text files should be read in ISO is a weird choice IMM.
附加 { type: "text/plain;charset=utf8" }
应该生成正确的 Content-Type
标头,当浏览器通过 blob URI 提供它时.Chrome 没有 open()
听起来像是一个错误.
Appending the { type: "text/plain;charset=utf8" }
should generate the proper Content-Type
header when they browsers will serve it through a blob URI. That Chrome doesn't with open()
sounds like a bug.
现在您可以通过在文本文件的开头添加 BOM 序列来解决此问题,以便 Chrome 将其检测为 UTF,即使没有Content-Type 信息:
Now you can workaround this by prepending a BOM sequence at the beginning of your text file, so that Chrome detects it as UTF, even without Content-Type info:
var BOM = new Uint8Array([0xEF,0xBB,0xBF]);
var b = new Blob([ BOM, "➀➁➂ Test" ]);
var url = URL.createObjectURL(b);
open(url);
var BOM = new Uint8Array([0xEF,0xBB,0xBF]);
var blob_BOM = new Blob([ BOM, "➀➁➂ Test" ]);
var url_BOM = URL.createObjectURL(blob_BOM);
// for demo we also create one version without BOM
var blob_noBOM = new Blob([ "➀➁➂ Test" ]);
var url_noBOM = URL.createObjectURL(blob_noBOM);
document.querySelector('.BOM').href = url_BOM;
document.querySelector('.no-BOM').href = url_noBOM;
// to check whether they contain the same data, apart from the BOM
(async() => {
const buf_BOM = await blob_BOM.slice(3).arrayBuffer(); // remove BOM sequence
const buf_noBOM = await blob_noBOM.arrayBuffer();
console.log( 'with BOM text data:' );
console.log( JSON.stringify( [...new Uint8Array( buf_BOM )] ) );
console.log( 'without BOM text data:' );
console.log( JSON.stringify( [...new Uint8Array( buf_noBOM )] ) );
})();
<a class="BOM">open file with BOM</a><br>
<a class="no-BOM">open file without BOM</a>
这篇关于在 Google Chrome 中指定 Blob 编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!