[英]Convert binary data to base64 with javascript
HTML5 enable you to store data locally which I think it is great. HTML5 使您能够在本地存储数据,我认为这很棒。 For example here is how you can use it:
例如,这里是你如何使用它:
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 is how 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.我知道我可以通过使用 html5 将图像包裹在画布周围然后将其转换为 base64string 来解决这个问题。 also I can make a specific service on the server that will send a base64 string data of that image (someImage.aspx).
我也可以在服务器上创建一个特定的服务,该服务将发送该图像的 base64 字符串数据(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.
我只想知道是否可以从服务器检索二进制数据并将其转换为 base64 字符串。
为防止出现“InvalidCharacterError”错误,您需要执行以下操作:
var base64EncodedStr = btoa(unescape(encodeURIComponent(rawData)));
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]));
});
试试btoa
功能:
var data = btoa(r);
This is old question, but could not find a better answer, so I wrote down this function.这是一个老问题,但找不到更好的答案,所以我写下了这个函数。 It will convert the Uint8Array directly to Base64 without converting it into a string before base64.
它会将 Uint8Array 直接转换为 Base64,而不会将其转换为 base64 之前的字符串。 Hope it will help someone.
希望它会帮助某人。
var encoder = new TextEncoder("ascii");
var decoder = new TextDecoder("ascii");
var base64Table = encoder.encode('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=');
function toBase64(dataArr){
var padding = dataArr.byteLength % 3;
var len = dataArr.byteLength - padding;
padding = padding > 0 ? (3 - padding) : 0;
var outputLen = ((len/3) * 4) + (padding > 0 ? 4 : 0);
var output = new Uint8Array(outputLen);
var outputCtr = 0;
for(var i=0; i<len; i+=3){
var buffer = ((dataArr[i] & 0xFF) << 16) | ((dataArr[i+1] & 0xFF) << 8) | (dataArr[i+2] & 0xFF);
output[outputCtr++] = base64Table[buffer >> 18];
output[outputCtr++] = base64Table[(buffer >> 12) & 0x3F];
output[outputCtr++] = base64Table[(buffer >> 6) & 0x3F];
output[outputCtr++] = base64Table[buffer & 0x3F];
}
if (padding == 1) {
var buffer = ((dataArr[len] & 0xFF) << 8) | (dataArr[len+1] & 0xFF);
output[outputCtr++] = base64Table[buffer >> 10];
output[outputCtr++] = base64Table[(buffer >> 4) & 0x3F];
output[outputCtr++] = base64Table[(buffer << 2) & 0x3F];
output[outputCtr++] = base64Table[64];
} else if (padding == 2) {
var buffer = dataArr[len] & 0xFF;
output[outputCtr++] = base64Table[buffer >> 2];
output[outputCtr++] = base64Table[(buffer << 4) & 0x3F];
output[outputCtr++] = base64Table[64];
output[outputCtr++] = base64Table[64];
}
var ret = decoder.decode(output);
output = null;
dataArr = null;
return ret;
}
//dataArr is a Uint8Array
function toBase64(dataArr){
return btoa(dataArr.reduce((data, val)=> {
return data + String.fromCharCode(val);
}, ''));
}
Fair and simply solution for modern day browsers现代浏览器的公平和简单的解决方案
fetch('https://picsum.photos/536/354', { method: 'GET', }) .then((data) => { // IMP to convert your json or other response to blob ( for this you have to check your api response is file / binary return data.blob() }) .then((data) => { var reader = new FileReader(); reader.onload = function() { var b64 = reader.result console.log("This is base64", b64) document.getElementById("imagetoShow").src = b64 } reader.readAsDataURL(data) }) .catch((error) => { error.text().then( errorMessage => { console.log(errorMessage) }) })
<image src="" width="200" height="200" id="imagetoShow"/>
Just fyi for code using node.js, it's just two simple function calls.仅供参考使用 node.js 的代码,它只是两个简单的函数调用。 I've wrapped them in a function for convenience.
为了方便起见,我将它们包装在一个函数中。
export function convertToBase64(bytes) {
return bytes.toString("base64");
}
export function convertFromBase64(str) {
return Buffer.from(str, "base64");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.