0

I have a react / node JS program with a material UI data table displaying rows from a mongoDB storage.

I would like users to be able to either download a single row, or, select multiple rows and then download all the files related to these rows.

The rows contain the location of the files in google cloud storage.

I tried to download the files in the react side using the following code:

const downloadFiles = () => {
    const pathReference = ref(storage, `${cellInfo.fileName}`);
    getDownloadURL(ref(storage, `${cellInfo.fileName}`))
      .then((pathReference) => {
        // `url` is the download URL for 'images/stars.jpg'

        // This can be downloaded directly:
        const xhr = new XMLHttpRequest();
        xhr.responseType = 'blob';
        xhr.onload = (event) => {
          const blob = xhr.response;
        };
        console.log(pathReference);
        xhr.open('GET', pathReference);
        xhr.send();
      })
      .catch((error) => {
        // Handle any errors
      });
  };

However this does not work at all. I set the cors policy as defined in the firebase storage tutorial. The path reference I get provided is valid, and, when I type it into my web browser it downloads the file, however this doesnt work when calling the function from my react app. Is this anything to do with me hosting it on local host?

  const downloadFiles = async () => {
    await axios
      .get(`http://localhost:3000/api/${location}/download/${cellInfo._id}`)
      .then((res) => {
        console.log(res);
      })
      .catch((err) => {
        console.log(err);
      });
  };

I tried this to link to the Node JS back end however still couldn't find a valid solution.

Joeboulton
  • 138
  • 8

1 Answers1

0

Update:

I managed to download single files using the below method (credit to this post)

 const downloadFiles = () => {
    const pathReference = ref(storage, `${cellInfo.fileName}`);
    getDownloadURL(ref(storage, `${cellInfo.fileName}`))
      .then((pathReference) => {
        // `url` is the download URL for 'images/stars.jpg'

        // This can be downloaded directly:
        const xhr = new XMLHttpRequest();
        xhr.responseType = 'blob';
        xhr.onload = (event) => {
          const blob = xhr.response;
          const link = document.createElement('a');
          link.href = pathReference;
             
          // Append to html link element page
          document.body.appendChild(link);

          // Start download
          link.click();

          // Clean up and remove the link
          link.parentNode.removeChild(link);
        };
        console.log(pathReference);
        xhr.open('GET', pathReference);
        xhr.send();
      })
      .catch((error) => {
        // Handle any errors
      });
  };
Joeboulton
  • 138
  • 8