How to download an image then store it on the device

Hey folks, could you suggest me a way of downloading images from a URL then store them with Capacitor (I am using Ionic Vue)?

I already reviewed Capacitor’s FileSystem API but given I don’t know how to pass it the image or file I am unable to use it.

Thanks!

The Ionic Vue first app tutorial is a great reference point as it implements something similar (photo gallery) that works on the web, ios, and android.

As a general strategy, download the image using fetch, convert it to base64 format (which Filesystem plugin requires), then write the file to the filesystem.

// retrieve the image
const response = await fetch("https://yoursite.com/image.png");
// convert to a Blob
const blob = await response.blob();
// convert to base64 data, which the Filesystem plugin requires
const base64Data = await convertBlobToBase64(blob) as string;
       
const savedFile = await Filesystem.writeFile({
  path: fileName,
  data: base64Data,
  directory: FilesystemDirectory.Data
});

// helper function
const convertBlobToBase64 = (blob: Blob) => new Promise((resolve, reject) => {
  const reader = new FileReader;
  reader.onerror = reject;
  reader.onload = () => {
    resolve(reader.result);
  };
 reader.readAsDataURL(blob);
});