-1

I'm following the firebase documentation for web to download the files related to a document in firestore. I practically pasted the code to achieve this, but when I click the element is not showing anything on console.

import { ref, getDownloadURL } from 'firebase/storage'

export const downloadMethod = (path) => {
    getDownloadURL(ref(storage, path))
        .then(url => {
            const xhr = new XMLHttpRequest();
            xhr.responseType = 'blob';
            xhr.onload = (event) => {
                const blob = xhr.response;
            };
            xhr.open('GET', url);
            xhr.send();
        })
        .catch(error => {
            throw error
        })
}

Before this I was having cors error but I solved it using

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

I want the website to download the requested file when I hit the button.

josmanuel
  • 403
  • 1
  • 3
  • 10
  • `catch(error => { throw error })` - please stop doing this. At least log the error before throwing it again – Konrad Nov 26 '22 at 17:43

2 Answers2

0

I guess you are missing the reference to the storage

import { getStorage, ref, getDownloadURL } from "firebase/storage";
const storage = getStorage();
...
Jay F.
  • 314
  • 4
0

Since the example in the documentation doesn't work, I looked for other methods in the documentation itself, and I managed to do exactly what I wanted by using getBlob()

This is my final function:

import { ref, getBlob } from 'firebase/storage'
import { storage } from '../firebase/firebase.config'

getBlob(ref(storage, 'files/MyFile.pdf'))
        .then((blob) => {
            const href = URL.createObjectURL(blob)
            const a = Object.assign(document.createElement('a'), {
                href,
                style: 'display:none',
                download: 'myFile.pdf' // This is where you set the name of the file you're about to download
            })
            a.click()

            URL.revokeObjectURL(href)
            a.remove()
        }).catch((error)=>{
            console.error(error)
        })

If you feel there's something I can change, you can feel free to tell me

josmanuel
  • 403
  • 1
  • 3
  • 10