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



Q1。在异步JavaScript和需要从客户端"获取"数据的情况下,为什么我们不能通过其属性src来编辑图像元素?

Q2.为什么Blob转换过程是必需的?

Q3.blob的角色是什么?

例如,从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作为<img>src

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

发生这种情况的一种常见情况是,当您允许用户从磁盘中选择文件时。文件选择器将允许您访问file对象,该对象是Blob,您可以将其加载到内存中。但是,您无法访问指向磁盘上文件的URI,因此在这种情况下无法设置src
在这里,您需要创建一个指向File对象的blob: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>

其他情况意味着您确实从前端创建了图像文件(例如使用画布(。

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

最新更新