我创建了一个下载和保存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>
发布于 2020-05-27 12:14:40
浏览器上下文中的文件API主要是围绕“读取”用例构建的。将文件写入客户端是出于安全考虑,在客户端没有无缝的API来实现这一点。
所以你可以在这里采取的方法是:
使用Ionic存储存储图像的blobs ( blobUrls
从方向上看,如下所示是您的主要功能:
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)});
};
};
https://stackoverflow.com/questions/62039652
复制