我创建了一个下载和保存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来做。
所以这里可以采取的方法是。
方向上像下面这样的东西将是你的主要功能。
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)});
};
};