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);
});
1 Like

Downloading the image is working fine for me, but the convertBlobToBase64 function don’t return anything on iOS and Android (Browser is working). It seems to stop at the reader.readAsDataURL(blob); but there’s no error logged.

Had to add this:

  if (request.response instanceof Blob) {
          const realFileReader = (reader as any)._realReader;
          if (realFileReader) {
            reader = realFileReader;
          }
        }

from

I use the same code and I have this error on IOS ‘error fetch TypeError: Origin capacitor://localhost is not allowed by Access-Control-Allow-Origin.’ So I change url and I test with this one “https://file-examples.com/storage/feeb72b10363daaeba4c0c9/2017/10/file_example_JPG_100kB.jpg” and I have a same error. So the problem isn’t from my server but from my IOS app.

I also add this confing.xml

<preference name="iosPersistentFileLocation" value="Library" />

info.plist

<key>UIFileSharingEnabled</key> <true/>
<key>LSSupportsOpeningDocumentsInPlace</key> <true/>

Thank you for your help.