获取后如何使用 FileReader 的 readAsArrayBuffer 方法并获得正确的大小?
How to use readAsArrayBuffer method from FileReader after fetch and get correct size?
我想从远程 URL 访问 ArrayBuffer。所以,我创建了函数:
fetch('some url')
.then(function(response) {
const file = new File([response], response.url, {type:'image/jpg'});
const reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function(e) {
const dataURL = reader.result;
console.log(dataURL);
};
})
而且我得到了错误的 ArrayBuffer 大小:ArrayBuffer(17 = length of my Url) 而不是实际图像大小(我认为大约 24000)。这里有什么问题?
如果您正在寻找 ArrayBuffer
of the requested resource, cut out the File
middleman and just have the response give you the Buffer directly with Body.arrayBuffer()
。
const url = "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
fetch(url)
.then(res => res.arrayBuffer())
.then(someBuffer => {
console.log(someBuffer.byteLength);
});
上面代码中使用的base64编码图像来自这里的这个答案:How to display Base64 images in HTML?.
我想从远程 URL 访问 ArrayBuffer。所以,我创建了函数:
fetch('some url')
.then(function(response) {
const file = new File([response], response.url, {type:'image/jpg'});
const reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function(e) {
const dataURL = reader.result;
console.log(dataURL);
};
})
而且我得到了错误的 ArrayBuffer 大小:ArrayBuffer(17 = length of my Url) 而不是实际图像大小(我认为大约 24000)。这里有什么问题?
如果您正在寻找 ArrayBuffer
of the requested resource, cut out the File
middleman and just have the response give you the Buffer directly with Body.arrayBuffer()
。
const url = "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
fetch(url)
.then(res => res.arrayBuffer())
.then(someBuffer => {
console.log(someBuffer.byteLength);
});
上面代码中使用的base64编码图像来自这里的这个答案:How to display Base64 images in HTML?.