Download an object
build a reference to an object
The reference makes use of:
- the storage service, which embeds the bucket's ID
- the object's name, which includes the extension
We build a reference with ref()
:
ref(storage, objectName)
ref(storage, "tts/2F1ZqipqaG0Mg....KoFq4Izjv.mp3") // a file
get a download HTTP URL
We generate the URL from which we use or download the object.
// client sdk
getDownloadURL(objectRef).then(url => ...)
// admin sdk
imgRef.getDownloadURL().then(url => ...)
using the download URL to display in page
If the object is a media, we may display it in the browser:
- we set the
src
attribute of an an img element to that URL. - we set the
src
attribute of an audio or video element to that URL
const img = document.getElementById("myImage")
img.src = url
using the download URL to allow direct download
We use fetch()
to download the object asynchronously, and get a blob of that object as a result. We then create a URL that refers to this local blob. Finally, we assign the URL to an anchor tag and add the download
attribute.
fetch(url)
.then((response) => response.blob())
.then((blob) => {
const blobUrl = URL.createObjectURL(blob)
// Get or create your anchor element
const downloadLink = document.getElementById("download-link") // Or create one
// Set the href to the blob URL
downloadLink.href = blobUrl
// Set the download attribute with desired filename
downloadLink.download = "your-filename.pdf"
// Clean up the blob URL when done (typically after click)
downloadLink.addEventListener("click", () => {
setTimeout(() => {
URL.revokeObjectURL(blobUrl)
}, 100)
})
})
.catch((error) => console.error("Error preparing download:", error))