[英]In Ionic Framework (v5), how do you use blob images saved in the data directory as inline and background images?
我創建了一個 function 用於下載和保存 blob 圖像,這樣如果用戶離線,圖像仍然可以渲染。 我必須這樣做,因為產品是通過 CMS 管理的。
這是 function:
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 可以做到這一點。
所以你可以在這里采取的方法是:
像下面這樣的定向內容將是您的主要 function:
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)});
};
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.