我从api中获取了一个随机图像(它是对象),我希望将它放入对象中的对象中,以处理该映像。当我是控制台日志“数据”时,一切正常,我可以看到这个图像对象,但是当我是控制台日志“data.image”时,控制台会返回一个空对象,它应该是获取的对象。我是初学者。
let data = {
image: {},
votes: []
}
async function getImage() {
let img = await fetch(data.getImgUrl, {
method: "GET",
})
const newImg = await img.json();
data.image = await newImg[0]
}当我是控制台记录“数据”时
console log :image{和以下是包含这些获取的数据}和选票的属性:
当我是控制台日志'data.image‘时
控制台日志:图像{空对象}
发布于 2019-12-28 17:21:40
获取一个图像,但尝试将其解码为JSON。这不管用。您需要执行如下操作(我还没有编写),我从这里获得了它--它使用的是arrayBuffer。
// we use this to get the immage from the buffer
function arrayBufferToBase64(buffer) {
var binary = '';
var bytes = [].slice.call(new Uint8Array(buffer));
bytes.forEach((b) => binary += String.fromCharCode(b));
return window.btoa(binary);
};
fetch(request, options).then((response) => {
response.arrayBuffer().then((buffer) => {
// make an image from the buffer
var imageStr = arrayBufferToBase64(buffer);
// use image where you want. e.g. out it into an image tag
document.querySelector('img').src = 'data:image/jpeg;base64,'+ imageStr;
});
});这可能也值得一读:流
https://stackoverflow.com/questions/59513030
复制相似问题