Télécharger des fichiers avec Cloud Storage sur le Web
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Cloud Storage for Firebase vous permet de télécharger rapidement et facilement des fichiers à partir d'un bucket Cloud Storage fourni et géré par Firebase.
Vous pouvez créer une référence en ajoutant des chemins d'accès enfants à la racine de votre bucket Cloud Storage, ou vous pouvez créer une référence à partir d'une URL gs:// ou https:// existante faisant référence à un objet dans 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');
Vous pouvez obtenir l'URL de téléchargement d'un fichier en appelant la méthode getDownloadURL() sur une référence 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});
Ces fonctions vous permettent de contourner le téléchargement à partir d'une URL et de renvoyer les données dans votre code. Cela permet un contrôle des accès plus précis via Firebase Security Rules.
Configuration CORS
Pour télécharger des données directement dans le navigateur, vous devez configurer votre bucket Cloud Storage pour l'accès multi-origine (CORS). Pour ce faire, utilisez l'outil de ligne de commande gsutil, que vous pouvez installer ici.
Si vous ne souhaitez aucune restriction basée sur le domaine (le scénario le plus courant), copiez ce JSON dans un fichier nommé cors.json :
Plusieurs raisons peuvent expliquer les erreurs de téléchargement, par exemple si le fichier n'existe pas ou si l'utilisateur n'est pas autorisé à y accéder.
Pour en savoir plus sur les erreurs, consultez la section Gérer les erreurs de la documentation.
Exemple complet
Vous trouverez ci-dessous un exemple complet de téléchargement avec gestion des erreurs :
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;}});
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/08/31 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Il n'y a pas l'information dont j'ai besoin","missingTheInformationINeed","thumb-down"],["Trop compliqué/Trop d'étapes","tooComplicatedTooManySteps","thumb-down"],["Obsolète","outOfDate","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Mauvais exemple/Erreur de code","samplesCodeIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/08/31 (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."]]