我想通过 javascript 将“base64”字符串转换为字节数组。
我收到了来自 URL 的字符串。
("data:image/jpeg;base64,/9j/4QN6RXhpZgAASUkqAAgAAAAIA)
我想将字符串转换为字节数组。因为我需要这个字节数组来发送 Rest API 端点。其余 API Content-type=application/octet-stream。
最佳答案
您可以使用 XMLHttpRequest
为您完成肮脏的工作:
var url = document.createElement("canvas").toDataURL(); // some data-uri
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = "arraybuffer";
xhr.onload = function() {
// result = ArrayBuffer, from here assign a view to it
if (xhr.status === 200) console.log(new Uint8Array(xhr.response));
};
xhr.send();
它比使用 atob()
的代码要多一点,但所有转换都在内部发生。它也是异步的,这有助于处理更大的数据 URI。
在较新的浏览器(支持它)中,您可以改用 fetch()
:
// note: atm not all browsers support these features.
fetch(document.createElement("canvas").toDataURL()) // pass in some data-uri
.then(function(response) {return response.arrayBuffer()})
.then(function(buffer) {
console.log(new Uint8Array(buffer));
});
关于javascript - 通过javascript将base64字符串转换为字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42360999/