Javascript 使用javascript将二进制数据转换为base64
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10982712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert binary data to base64 with javascript
提问by Tono Nam
HTML5 enable you to store data locally which I think it is great. For example here is how you can use it:
HTML5 使您能够在本地存储数据,我认为这很棒。例如,这里是如何使用它:
var store = window.localStorage;
store.setItem('foo', "hellow world");
var test = store.getItem('foo');
// test should = "hellow world"
In html you can dynamically display an image by settig its source to:
在 html 中,您可以通过将其来源设置为动态显示图像:
"data:image/jpg;base64," + (base64string)
So my question ishow can I convert binary data to a base64 string so that I can take advantage of html5 local storage?
所以我的问题是如何将二进制数据转换为 base64 字符串,以便我可以利用 html5 本地存储?
For example it will be great if I could:
例如,如果我可以:
$.ajax({
url: 'someImage.png',
type: 'POST',
success: function (r) {
// here I want to convert r to a base64 string !
// r is not binary so maybe I have to use a different approach
var data = ConvertToBase64(r);
document.getElementById("img").src = "data:image/png;base64," + data;
},
});
I know I could solve this problem by wrapping the image around a canvas using html5 then converting that to base64string. also I can make a specific service on the server that will send a base64 string data of that image (someImage.aspx).I just want to know if it will by possible to retrieve binary data from a server and convert that to a base64 string.
我知道我可以通过使用 html5 将图像包裹在画布周围然后将其转换为 base64string 来解决这个问题。我也可以在服务器上创建一个特定的服务,该服务将发送该图像的 base64 字符串数据(someImage.aspx)。我只想知道是否可以从服务器检索二进制数据并将其转换为 base64 字符串。
回答by Frane Poljak
To prevent 'InvalidCharacterError' error, you need to do this:
为了防止 'InvalidCharacterError' 错误,你需要这样做:
var base64EncodedStr = btoa(unescape(encodeURIComponent(rawData)));
回答by Bastian Voigt
Use a FileReader to encode your image as a data URL:
使用 FileReader 将您的图像编码为数据 URL:
jQuery.ajax({...})
.done(function (r) {
var reader = new FileReader(
reader.onload = (function(self) {
return function(e) {
document.getElementById("img").src = e.target.result;
}
})(this);
reader.readAsDataURL(new Blob([r]));
});