我是否正确地在JavaScript中使用.createObjectURL使用的Blob对象?

问题描述 投票:1回答:1

我正在尝试从.png文件获取响应,并使用简单的JS准备它作为DOM中的图像放置。但...

ready().then(() => {
  fetch(`/images/logo.png`)
  .then(response =>{
    if (response) {
      let imageBlob = response.blob();
      let objectURL = URL.createObjectURL(imageBlob);
...

给我......

Uncaught (in promise) TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided.
    at fetch.then.response (fetchImage.js:6)
    at <anonymous>
fetch.then.response       @ fetchImage.js:6
Promise resolved (async)
ready.then                @ fetchImage.js:3
Promise resolved (async)
(anonymous)               @ fetchImage.js:1

如果我扔进console.log(response),我可以看到我得到了完整的回复。那console.log(imageBlob)将返回Promise {<resolved>: Blob(3737)}。那么我哪里出错了?

javascript image dom
1个回答
0
投票

正确使用fetch,response.blob()返回一个Promise - 所以,当你处理fetch承诺时处理它

ready().then(() => {
  fetch(`/images/logo.png`)
  .then(response => response.blob())
  .then(imageBlob => {
    let objectURL = URL.createObjectURL(imageBlob);
    //...
  });
});

还是更好

ready()
.then(() => fetch(`/images/logo.png`))
.then(response => response.blob())
.then(imageBlob => {
  let objectURL = URL.createObjectURL(imageBlob);
  //...
});

或使用async/await

ready()
.then(() => fetch(`/images/logo.png`))
.then(async (response) => {
  let imageBlob = await response.blob();
  let objectURL = URL.createObjectURL(imageBlob);
  //...
});
© www.soinside.com 2019 - 2024. All rights reserved.