skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    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


  2. I guess you are missing the reference to the storage

    import { getStorage, ref, getDownloadURL } from "firebase/storage";
    const storage = getStorage();
    ...
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search