Skip to content
Advertisement

How to download multiple files from firebase using downloadURL in javascript?

I have this code:

 fetch("/downloadFiles?" + new URLSearchParams({ items: currCart })) // fetching from my server all the download urls 
.then((res) => res.json())
.then((data) => { // data is returned as an object - {items: [array of urls]}
data.items.forEach((element, index) => {
  var link = document.createElement("a");
  link.download = currCart[index];
  link.href = element;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  });
})}

but instead of downloading the files it opens them in my browser. The currCart[index] is just the wanted name of the downloaded file.

Any suggestions?

Advertisement

Answer

To download a file, we need to create a Cloud Storage reference to the file we want to download, to do that, you can create a reference by appending child paths to the root of your Cloud Storage bucket to then, download data via URL calling the getDownloadURL() method on a Cloud Storage reference.

If you want to download data directly from the SDK (from version 9.5 and higher) it already provides these functions for direct download using getBlob(), getStream() available only in Node.js, getBlob() only for browser-like environments.

But if you need to download data directly in the browser, you must configure your Cloud Storage bucket for cross-origin access (CORS). Add this JSON to a file named cors.json.

[
  {
    "origin": ["*"],
    "method": ["GET"],
    "maxAgeSeconds": 3600
  }
]

To deploy these restrictions and set your bucket, run the following command:

$ gsutil cors set cors.json gs://<your-cloud-storage-bucket>

JS file

import { getStorage, ref, getDownloadURL } from "firebase/storage";

// Create a reference to the file we want to download
const storage = getStorage();
const starsRef = ref(storage, 'images/stars.jpg');

// Get the download URL
getDownloadURL(starsRef)
  .then((url) => {
    // <---------------- Insert url file here!
  })
  .catch((error) => {
    // A full list of error codes is available at
    // https://firebase.google.com/docs/storage/web/handle-errors
    switch (error.code) {
      case 'storage/object-not-found':
        // File doesn't exist
        break;
      case 'storage/unauthorized':
        // User doesn't have permission to access the object
        break;
      case 'storage/canceled':
        // User canceled the upload
        break;

      // ...

      case 'storage/unknown':
        // Unknown error occurred, inspect the server response
        break;
    }
  });

Doesn’t matter what format you want to use, just insert the URL or the reference link (PDF, GIF, image, video, etc) of the file we want to show inside the function getDownloadURL() and same process with the <iframe>.

PDF file for example in HTML document is <a href=""> tag with href attribute for the url or path if you are self hosting the file:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <h1>PDF Example</h1>
    <p>Download PDF file <a href="/assets/pdf/5cb701example.pdf">here</a></p>
  </body>
</html>
Advertisement