Ionic 5 - Save PDF BLOB to filesystem

I have been trying to download a file with Ionic for several hours. Unfortunately it did not work until now. I am using ionic with React and trying to save a blob. This is my code so far:

import {File} from "@ionic-native/file";

/* Some react code here */

axios({
  url: link,
  method: "GET",
  responseType: "blob",
})
.then((response) => {
  File.writeFile(
    File.dataDirectory,
    "test.pdf",
    new Blob([response.data]),
    {
      replace: true,
    }
  )
    .then(() => {
      console.log("Saved");
    })
    .catch((error) => {
      console.log(error);
      console.log("Not saved");
    });
})
.catch((error) => {
  console.log(error);
});

Can someone please help me? Did I forget something? Or do I have to set special permissions?

1 Like

Capacitor provides its own Filesystem API, no need to use the @ionic-native package.

Okay guys I found a solution for my problem. My code was saving the file correctly but I didn’t see it, because it was saved in the dataDirectory, which is not public. Here is my updated code, which saves the file in the downloads folder:

import {File} from "@ionic-native/file";
import {FileOpener} from "@ionic-native/file-opener";

/* Some react code here */

axios({
  url: link,
  method: "GET",
  responseType: "blob",
})
  .then((response) => {
    if (platform === "web") {
      const url = window.URL.createObjectURL(
        new Blob([response.data])
      );
      const link = window.document.createElement("a");
      link.href = url;
      link.setAttribute("download", fileName);
      window.document.body.appendChild(link);
      link.click();
      link.remove();
    } else {
      return File.writeFile(
        File.externalRootDirectory + "/Download",
        fileName,
        new Blob([response.data]),
        {
          replace: true,
        }
      );
    }
  })
  .then(() => {
      return FileOpener.open(
      File.externalRootDirectory + "/Download/" + fileName,
      "application/pdf"
    );
  })
  .catch((error) => {
    console.log(error);
  });
}}

Note: When the user is on the web, I simply download the file.

1 Like