【发布时间】:2020-08-01 18:09:28
【问题描述】:
第一季度。在异步 JavaScript 和需要从客户端“获取”数据的情况下,为什么我们不能通过属性src 来编辑我们的图像元素?
第二季度。为什么必须经过 Blob 转换过程?
第三季度。什么是 blob 角色?
例如从 JSON 中检索图像文件。 (顺便说一句,我是从 MDN 网页中提取的,请注意 cmets)
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);
});
}
【问题讨论】:
-
你可以。你是对的,对于这种情况,它完全没用。该代码仅用于说明如何使用 createObjectURL API。
-
但是 createObjectURL 对于图像之外的一些其他情况也很有用。假设您制作了一个 Web 应用程序,它允许您的用户拖放任意文件,然后将其压缩并提供 zip 文件的下载链接。它可以在客户端使用纯js完成,不涉及服务器。对于这种情况,createObjectURL 将是一个有意义的部分。
标签: javascript json blob asynchronous-javascript