javascript - 为什么使用 `URL.createObjectURL(blob)` 而不是 `image.src` ?

标签 javascript json blob asynchronous-javascript

Q1。在异步 JavaScript 的上下文中,需要从 中“获取”数据客户端 , 为什么我们不能通过它的属性 src 来编辑我们的图像元素? ?

Q2。为什么必须经过 Blob 转换过程?

Q3。什么是 blob Angular 色?

例如从 JSON 中检索图像文件。 (顺便说一句,我是从 MDN 网页中提取的,请注意评论)


  function fetchBlob(product) {
    // construct the URL path to the image file from the product.image property
    let url = 'images/' + product.image;
    // Use fetch to fetch the image, and convert the resulting response to a blob
    // Again, if any errors occur we report them in the console.
    fetch(url).then(function(response) {
        return response.blob();
    }).then(function(blob) {
      // Convert the blob to an object URL — this is basically an temporary internal URL
      // that points to an object stored inside the browser
      let objectURL = URL.createObjectURL(blob);
      // invoke showProduct
      showProduct(objectURL, product);
    });
  }

最佳答案

如果可以,则直接将 url 用作 src您的<img> .

使用 blob:仅当您有一个保存图像文件的 Blob 并且您需要显示它时,URL 才有用。

发生这种情况的一种常见情况是您允许用户从他们的磁盘中选择一个文件。文件选择器将允许您访问 File 对象,它是一个 Blob,您可以将其加载到内存中。但是,您无权访问指向磁盘上文件的 URI,因此您无法设置 src在这种情况下。
这里需要创建一个blob:指向 File 对象的 URI。浏览器内部获取机制将能够从该 URL 检索用户磁盘上的数据,从而显示该图像:

document.querySelector('input').onchange = e => {
  const file = e.target.files[0]; // this Object holds a reference to the file on disk
  const url = URL.createObjectURL(file); // this points to the File object we just created
  document.querySelector('img').src = url;
};
<input type="file" accepts="image/*">
<img>


其他情况暗示你做了创建 来自前端的图像文件(例如使用 Canvas )。

但是,如果您的 Blob 只是从您的服务器获取资源的结果,并且您的服务器不需要特殊请求来提供它,那么确实,没​​有真正的意义......

关于javascript - 为什么使用 `URL.createObjectURL(blob)` 而不是 `image.src` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61302149/

相关文章:

Jquery - CodeIgniter 如何为 blob 提供文件扩展名

Android 从 Azure Blob 存储下载导致文件无效

javascript - 将 JSON 字符串传递给 JavaScript

javascript - AngularJS 中的日期 json 对象 json

javascript - 如何解决 for 循环中的所有 promise ?

javascript - 如何防止浏览器重复获取相同的href

python - 如何 JSON 序列化 Pydantic BaseModel 中的 ENum 类

database - 做或不做:将图像存储在数据库中

javascript - 如果窗口关闭,则打开一个函数

javascript - 在输入字段中输入文本时,有没有办法更改 div 的背景?