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

时间:2018-02-21 23:43:47

标签: javascript image dom

我正在尝试从.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)}。 那我哪里出错呢?

1 个答案:

答案 0 :(得分: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);
  //...
});