Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
698 views
in Technique[技术] by (71.8m points)

javascript - Specifying blob encoding in Google Chrome

The following code (vendor normalized) works perfectly fine and displays "??? Test" in Firefox 8, but displays "a?€a?a?? 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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Gecko (Firefox), WebKit (Safari, Chrome) and Opera support the non-standard btoa function for encoding a string in base 64. In order to get a base 64 string containing a string encoded as UTF-8 you need to use the encodeURIComponent-unescape trick. encodeURIComponent encodes a string as UTF-8 URL but unescape decodes each %xx as a single character. btoa expects a binary string of whatever encoding you want.

var base64 = btoa(unescape(encodeURIComponent(data)));
window.open("data:text/plain;charset=UTF-8;base64,"+base64,"UTF-8 Text");

Of course this does not work in IE, but I think IE 10 will support the Blob-API. Who knows how it will handle encodings.

PS: IE seems not to be able to window.open data:-urls and would have a ridiculous small url length limitation anyway.

PPS: This works for me in Chrome:

var b = new Blob(["??? Test"],{encoding:"UTF-8",type:"text/plain;charset=UTF-8"});
var url = URL.createObjectURL(b);
window.open(url,"_blank","");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...