Crie uma referência anexando caminhos filhos à raiz do bucket do Cloud Storage ou crie uma referência usando um URL gs:// ou https:// atual ao referenciar um objeto no Cloud Storage.
Web
import{getStorage,ref}from"firebase/storage";// Create a reference with an initial file path and nameconststorage=getStorage();constpathReference=ref(storage,'images/stars.jpg');// Create a reference from a Google Cloud Storage URIconstgsReference=ref(storage,'gs://bucket/images/stars.jpg');// Create a reference from an HTTPS URL// Note that in the URL, characters are URL escaped!consthttpsReference=ref(storage,'https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg');
// Create a reference with an initial file path and namevarstorage=firebase.storage();varpathReference=storage.ref('images/stars.jpg');// Create a reference from a Google Cloud Storage URIvargsReference=storage.refFromURL('gs://bucket/images/stars.jpg');// Create a reference from an HTTPS URL// Note that in the URL, characters are URL escaped!varhttpsReference=storage.refFromURL('https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg');
Você pode conseguir o URL de download de um arquivo chamando o método getDownloadURL() em uma referência do Cloud Storage.
Web
import{getStorage,ref,getDownloadURL}from"firebase/storage";conststorage=getStorage();getDownloadURL(ref(storage,'images/stars.jpg')).then((url)=>{// `url` is the download URL for 'images/stars.jpg'// This can be downloaded directly:constxhr=newXMLHttpRequest();xhr.responseType='blob';xhr.onload=(event)=>{constblob=xhr.response;};xhr.open('GET',url);xhr.send();// Or inserted into an <img> elementconstimg=document.getElementById('myimg');img.setAttribute('src',url);}).catch((error)=>{// Handle any errors});
storageRef.child('images/stars.jpg').getDownloadURL().then((url)=>{// `url` is the download URL for 'images/stars.jpg'// This can be downloaded directly:varxhr=newXMLHttpRequest();xhr.responseType='blob';xhr.onload=(event)=>{varblob=xhr.response;};xhr.open('GET',url);xhr.send();// Or inserted into an <img> elementvarimg=document.getElementById('myimg');img.setAttribute('src',url);}).catch((error)=>{// Handle any errors});
Usando essas funções, é possível ignorar o download a partir de um URL e, em vez disso,
retornar os dados no código. Isso permite um controle de acesso refinado com as Firebase Security Rules.
Configuração do CORS
Para baixar dados diretamente no navegador, configure o bucket do Cloud Storage para acesso de origem cruzada (CORS, na sigla em inglês). Isso pode ser feito com a ferramenta de linha de comando gsutil, que pode ser instalada por aqui.
Se você não quiser restrições baseadas em domínio, que é o cenário mais comum, copie este JSON em um arquivo chamado cors.json:
Durante os downloads, é possível que erros ocorram por vários motivos. Por exemplo, o
arquivo não existe ou o usuário não tem permissão para acessá-lo.
Saiba mais sobre erros na seção
Tratar erros.
Exemplo completo
Um exemplo completo de um erro no download é mostrado abaixo:
Web
import{getStorage,ref,getDownloadURL}from"firebase/storage";// Create a reference to the file we want to downloadconststorage=getStorage();conststarsRef=ref(storage,'images/stars.jpg');// Get the download URLgetDownloadURL(starsRef).then((url)=>{// Insert url into an <img> tag to "download"}).catch((error)=>{// A full list of error codes is available at// https://firebase.google.com/docs/storage/web/handle-errorsswitch(error.code){case'storage/object-not-found':// File doesn't existbreak;case'storage/unauthorized':// User doesn't have permission to access the objectbreak;case'storage/canceled':// User canceled the uploadbreak;// ...case'storage/unknown':// Unknown error occurred, inspect the server responsebreak;}});
// Create a reference to the file we want to downloadvarstarsRef=storageRef.child('images/stars.jpg');// Get the download URLstarsRef.getDownloadURL().then((url)=>{// Insert url into an <img> tag to "download"}).catch((error)=>{// A full list of error codes is available at// https://firebase.google.com/docs/storage/web/handle-errorsswitch(error.code){case'storage/object-not-found':// File doesn't existbreak;case'storage/unauthorized':// User doesn't have permission to access the objectbreak;case'storage/canceled':// User canceled the uploadbreak;// ...case'storage/unknown':// Unknown error occurred, inspect the server responsebreak;}});
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Não contém as informações de que eu preciso","missingTheInformationINeed","thumb-down"],["Muito complicado / etapas demais","tooComplicatedTooManySteps","thumb-down"],["Desatualizado","outOfDate","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Problema com as amostras / o código","samplesCodeIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-09-05 UTC."],[],[],null,["\u003cbr /\u003e\n\nCloud Storage for Firebase allows you to quickly and easily download\nfiles from a [Cloud Storage](//cloud.google.com/storage)\nbucket provided and managed by Firebase.\n| **Note:** By default, a Cloud Storage for Firebase bucket requires Firebase Authentication to perform any action on the bucket's data or files. You can change your Firebase Security Rules for Cloud Storage to [allow unauthenticated access for specific situations](/docs/storage/security/rules-conditions#public). However, for most situations, we strongly recommend [restricting access and setting up robust security rules](/docs/storage/security/get-started) (especially for production apps). Note that if you use Google App Engine and have a default Cloud Storage bucket with a name format of `*.appspot.com`, you may need to consider [how your security rules impact access to App Engine files](/docs/storage/gcp-integration#security-rules-and-app-engine-files).\n\nCreate a Reference\n\nTo download a file, first\n[create a Cloud Storage reference](/docs/storage/web/create-reference)\nto the file you want to download.\n\nYou can create a reference by appending child paths to the root of your\nCloud Storage bucket, or you can create a reference from an existing\n`gs://` or `https://` URL referencing an object in Cloud Storage. \n\nWeb \n\n```javascript\nimport { getStorage, ref } from \"firebase/storage\";\n\n// Create a reference with an initial file path and name\nconst storage = getStorage();\nconst pathReference = ref(storage, 'images/stars.jpg');\n\n// Create a reference from a Google Cloud Storage URI\nconst gsReference = ref(storage, 'gs://bucket/images/stars.jpg');\n\n// Create a reference from an HTTPS URL\n// Note that in the URL, characters are URL escaped!\nconst httpsReference = ref(storage, 'https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg'); https://github.com/firebase/snippets-web/blob/467eaa165dcbd9b3ab15711e76fa52237ba37f8b/snippets/storage-next/download-files/storage_download_create_ref.js#L8-L19\n```\n\nWeb \n\n```javascript\n// Create a reference with an initial file path and name\nvar storage = firebase.storage();\nvar pathReference = storage.ref('images/stars.jpg');\n\n// Create a reference from a Google Cloud Storage URI\nvar gsReference = storage.refFromURL('gs://bucket/images/stars.jpg');\n\n// Create a reference from an HTTPS URL\n// Note that in the URL, characters are URL escaped!\nvar httpsReference = storage.refFromURL('https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg'); https://github.com/firebase/snippets-web/blob/467eaa165dcbd9b3ab15711e76fa52237ba37f8b/storage/download-files.js#L6-L15\n```\n\nDownload Data via URL\n\nYou can get the download URL for a file by calling the\n`getDownloadURL()` method on a Cloud Storage reference. \n\nWeb \n\n```javascript\nimport { getStorage, ref, getDownloadURL } from \"firebase/storage\";\n\nconst storage = getStorage();\ngetDownloadURL(ref(storage, 'images/stars.jpg'))\n .then((url) =\u003e {\n // `url` is the download URL for 'images/stars.jpg'\n\n // This can be downloaded directly:\n const xhr = new XMLHttpRequest();\n xhr.responseType = 'blob';\n xhr.onload = (event) =\u003e {\n const blob = xhr.response;\n };\n xhr.open('GET', url);\n xhr.send();\n\n // Or inserted into an \u003cimg\u003e element\n const img = document.getElementById('myimg');\n img.setAttribute('src', url);\n })\n .catch((error) =\u003e {\n // Handle any errors\n });https://github.com/firebase/snippets-web/blob/467eaa165dcbd9b3ab15711e76fa52237ba37f8b/snippets/storage-next/download-files/storage_download_via_url.js#L8-L30\n```\n\nWeb \n\n```javascript\nstorageRef.child('images/stars.jpg').getDownloadURL()\n .then((url) =\u003e {\n // `url` is the download URL for 'images/stars.jpg'\n\n // This can be downloaded directly:\n var xhr = new XMLHttpRequest();\n xhr.responseType = 'blob';\n xhr.onload = (event) =\u003e {\n var blob = xhr.response;\n };\n xhr.open('GET', url);\n xhr.send();\n\n // Or inserted into an \u003cimg\u003e element\n var img = document.getElementById('myimg');\n img.setAttribute('src', url);\n })\n .catch((error) =\u003e {\n // Handle any errors\n });https://github.com/firebase/snippets-web/blob/467eaa165dcbd9b3ab15711e76fa52237ba37f8b/storage/download-files.js#L23-L42\n```\n\nDownload Data Directly from the SDK\n\nFrom version 9.5 and higher, the SDK provides these functions for direct\ndownload:\n\n- [`getBlob()`](/docs/reference/js/storage#getblob)\n- [`getBytes()`](/docs/reference/js/storage#getbytes)\n- [`getStream()`](/docs/reference/js/storage#getstream)\n\nUsing these functions, you can bypass downloading from a URL, and instead\nreturn data in your code. This allows for finer-grained access control via\n[Firebase Security Rules](/docs/storage/security).\n| **Note:** `getStream()` is available only for Node.js, and `getBlob()` is available only for browser-like environments.\n\nCORS Configuration\n\nTo download data directly in the browser, you must configure your\nCloud Storage bucket for cross-origin access (CORS). This can be done\nwith the `gsutil` command line tool, which you can\n[install from here](//cloud.google.com/storage/docs/gsutil_install).\n\nIf you don't want any domain-based restrictions (the most common scenario),\ncopy this JSON to a file named `cors.json`: \n\n```scdoc\n[\n {\n \"origin\": [\"*\"],\n \"method\": [\"GET\"],\n \"maxAgeSeconds\": 3600\n }\n]\n```\n\n\u003cbr /\u003e\n\nRun `gsutil cors set cors.json gs://\u003cyour-cloud-storage-bucket\u003e` to deploy\nthese restrictions.\n\nFor more information, refer to the\n[Google Cloud Storage documentation](//cloud.google.com/storage/docs/cross-origin).\n\nHandle Errors\n\nThere are a number of reasons why errors may occur on download, including the\nfile not existing, or the user not having permission to access the desired file.\nMore information on errors can be found in the\n[Handle Errors](/docs/storage/web/handle-errors)\nsection of the docs.\n\nFull Example\n\nA full example of a download with error handling is shown below: \n\nWeb \n\n```javascript\nimport { getStorage, ref, getDownloadURL } from \"firebase/storage\";\n\n// Create a reference to the file we want to download\nconst storage = getStorage();\nconst starsRef = ref(storage, 'images/stars.jpg');\n\n// Get the download URL\ngetDownloadURL(starsRef)\n .then((url) =\u003e {\n // Insert url into an \u003cimg\u003e tag to \"download\"\n })\n .catch((error) =\u003e {\n // A full list of error codes is available at\n // https://firebase.google.com/docs/storage/web/handle-errors\n switch (error.code) {\n case 'storage/object-not-found':\n // File doesn't exist\n break;\n case 'storage/unauthorized':\n // User doesn't have permission to access the object\n break;\n case 'storage/canceled':\n // User canceled the upload\n break;\n\n // ...\n\n case 'storage/unknown':\n // Unknown error occurred, inspect the server response\n break;\n }\n });https://github.com/firebase/snippets-web/blob/467eaa165dcbd9b3ab15711e76fa52237ba37f8b/snippets/storage-next/download-files/storage_download_full_example.js#L8-L39\n```\n\nWeb \n\n```javascript\n// Create a reference to the file we want to download\nvar starsRef = storageRef.child('images/stars.jpg');\n\n// Get the download URL\nstarsRef.getDownloadURL()\n.then((url) =\u003e {\n // Insert url into an \u003cimg\u003e tag to \"download\"\n})\n.catch((error) =\u003e {\n // A full list of error codes is available at\n // https://firebase.google.com/docs/storage/web/handle-errors\n switch (error.code) {\n case 'storage/object-not-found':\n // File doesn't exist\n break;\n case 'storage/unauthorized':\n // User doesn't have permission to access the object\n break;\n case 'storage/canceled':\n // User canceled the upload\n break;\n\n // ...\n\n case 'storage/unknown':\n // Unknown error occurred, inspect the server response\n break;\n }\n});https://github.com/firebase/snippets-web/blob/467eaa165dcbd9b3ab15711e76fa52237ba37f8b/storage/download-files.js#L50-L78\n```\n\nYou can also [get or update metadata](/docs/storage/web/file-metadata)\nfor files that are stored in Cloud Storage."]]