In Ionic Framework (v5), how do you use blob images saved in the data directory as inline and background images?

I have also posted this on Stack Overflow

I created a function for downloading and saving the blob images so that if the user is offline, the images can still be rendered. I have to do it this way as the products are managed via a CMS.

Here is the 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();
            });
        }
      });
  });
}

Here is the page view I would like the images to render:

<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>

Can you wrap this in a quick sample app for debugging? It’s not really easy to tell what the issue is from just that.

Hi @mhartington , I was mainly after advice rather than needing to debug something. If I can get a sample app up somewhere then I will. I thought my code snippets up there would be enough as essentially I am after a function to be able to return my productImage from my data directory where it is stored as a blob.

Typically dont use blobs, as it’s just binary data. You would convert the blog data to base64 or write the blog to a file.

This code really makes my head hurt, and I would love to see it rearchitected to eliminate manual Promise creation, which should be fairly straightforward using either Promise.all or RxJS’s forkJoin operator. That being said, you might want to look at the Ionic Webview plugin, specifically the convertFileSrc method, for assistance with your main stated goal here.

We’ve used something like this in the past to convert blob images to base64:

return new Promise((resolve, reject) => {
    let reader = new FileReader();
    reader.onloadend = () => {
        resolve(reader.result);
    }
    reader.readAsDataURL(response.data); // Substitute response.data with your blob data
});