在 Ionic Framework (v5) 中,如何使用保存在数据目录中的 blob 图像作为内联和背景图像?



我创建了一个用于下载和保存 blob 图像的函数,以便在用户脱机时仍然可以渲染图像。我必须这样做,因为产品是通过CMS管理的。

这是函数:

downloadProductImages(products) {
return new Promise((resolve, reject) => {
this.platform.ready()
.then(() => {
for (let i = 0; i < products.length; i++) {
const productImageUrl = SERVER_URL + products[i].imageUrl,
fileName = products[i].image;
this.http
.sendRequest(productImageUrl, {
method: 'download',
filePath: this.directoryPath + fileName,
responseType: 'blob'
})
.then((response: any) => {
this.file.writeFile(this.directory, fileName, response, {replace: true})
.then(_ => {
resolve();
})
.catch(error => {
reject();
});
})
.catch(error => {
reject();
});
}
});
});
}

这是我希望图像呈现的页面视图:

<div [ngStyle]="{'background-image': 'url('' + (productImage !== '' ? productImage : '../../assets/images/image-not-available.png' | sanitizeUrl) + '')'}">
<ion-row>
<ion-col size="12" size-sm="6">
<div class="show-mobile">
<img [src]="(productImage !== '' ? productImage : '../../assets/images/image-not-available.png' | sanitizeUrl)" class="img-responsive">
</div>
</ion-col>
</ion-row>
</div>

浏览器上下文中的文件 API 主要围绕"读取"用例构建。将文件写入客户端计算机受到安全问题的约束,并且在客户端没有无缝的 API 来执行此操作。

因此,您可以在此处采取的方法是:

  • 使用 Ionic Storage 存储图像的 blob(localForage 支持将 blob 存储在 indexeddb 中(
  • 在应用程序启动时检查存储的 blob 并通过运行 foreach 循环来恢复本地缓存并创建 blobUrl
  • 如果应用处于脱机状态,则为 img 元素创建条件以从本地 blobUrl 读取

从方向上讲,下面这样的东西将是你的主要功能:

async cacheImagesLocally() {
// not sure what your products array looks like, but just for example here:
const products = [{
image: "image0",
imageUrl: "someURL"
}];
// this one should probably be a property in your class:
const localBlobUrlsCache = [];
for (const product of products) {
let localBlob = await this.storage.get(product.image);
if (!localBlob) {
const productImageUrl = SERVER_URL + product.imageUrl;
const fileName = product.image;
localBlob = await this.http.sendRequest(productImageUrl, {
method: 'download',
filePath: this.directoryPath + fileName,
responseType: 'blob'
});
};
localBlobUrlsCache.push({image: product.image, blobUrl: URL.createObjectURL(localBlob)});
};
};

最新更新