Cloud Storage for Firebase ti consente di scaricare file in modo rapido e semplice da un bucket Cloud Storage fornito e gestito da Firebase.
Crea un riferimento
Per scaricare un file, crea innanzitutto un riferimento Cloud Storage per il file che desideri scaricare.
Puoi creare un riferimento aggiungendo percorsi secondari alla radice del tuo bucket Cloud Storage oppure puoi creare un riferimento da un URL gs://
o https://
esistente che fa riferimento a un oggetto in Cloud Storage.
Web modular API
import { getStorage, ref } from "firebase/storage"; // Create a reference with an initial file path and name const storage = getStorage(); const pathReference = ref(storage, 'images/stars.jpg'); // Create a reference from a Google Cloud Storage URI const gsReference = ref(storage, 'gs://bucket/images/stars.jpg'); // Create a reference from an HTTPS URL // Note that in the URL, characters are URL escaped! const httpsReference = ref(storage, 'https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg');
Web namespaced API
// Create a reference with an initial file path and name var storage = firebase.storage(); var pathReference = storage.ref('images/stars.jpg'); // Create a reference from a Google Cloud Storage URI var gsReference = storage.refFromURL('gs://bucket/images/stars.jpg'); // Create a reference from an HTTPS URL // Note that in the URL, characters are URL escaped! var httpsReference = storage.refFromURL('https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg');
Scarica i dati tramite URL
Puoi ottenere l'URL di download di un file chiamando il metodo getDownloadURL()
su un riferimento Cloud Storage.
Web modular API
import { getStorage, ref, getDownloadURL } from "firebase/storage"; const storage = getStorage(); getDownloadURL(ref(storage, 'images/stars.jpg')) .then((url) => { // `url` is the download URL for 'images/stars.jpg' // This can be downloaded directly: const xhr = new XMLHttpRequest(); xhr.responseType = 'blob'; xhr.onload = (event) => { const blob = xhr.response; }; xhr.open('GET', url); xhr.send(); // Or inserted into an <img> element const img = document.getElementById('myimg'); img.setAttribute('src', url); }) .catch((error) => { // Handle any errors });
Web namespaced API
storageRef.child('images/stars.jpg').getDownloadURL() .then((url) => { // `url` is the download URL for 'images/stars.jpg' // This can be downloaded directly: var xhr = new XMLHttpRequest(); xhr.responseType = 'blob'; xhr.onload = (event) => { var blob = xhr.response; }; xhr.open('GET', url); xhr.send(); // Or inserted into an <img> element var img = document.getElementById('myimg'); img.setAttribute('src', url); }) .catch((error) => { // Handle any errors });
Scarica i dati direttamente dall'SDK
Dalla versione 9.5 e successive, l'SDK fornisce queste funzioni per il download diretto:
Utilizzando queste funzioni, puoi ignorare il download da un URL e restituire invece i dati nel tuo codice. Ciò consente un controllo degli accessi più capillare tramite le regole di sicurezza Firebase .
Configurazione CORS
Per scaricare i dati direttamente nel browser, è necessario configurare il bucket Cloud Storage per l'accesso multiorigine (CORS). Questo può essere fatto con lo strumento da riga di comando gsutil
, che puoi installare da qui .
Se non desideri alcuna restrizione basata sul dominio (lo scenario più comune), copia questo JSON in un file denominato cors.json
:
[ { "origin": ["*"], "method": ["GET"], "maxAgeSeconds": 3600 } ]
Esegui gsutil cors set cors.json gs://<your-cloud-storage-bucket>
per distribuire queste restrizioni.
Per ulteriori informazioni, fare riferimento alla documentazione di Google Cloud Storage .
Gestire gli errori
Esistono diversi motivi per cui potrebbero verificarsi errori durante il download, incluso il file inesistente o l'utente che non dispone dell'autorizzazione per accedere al file desiderato. Ulteriori informazioni sugli errori sono disponibili nella sezione Gestione degli errori della documentazione.
Esempio completo
Di seguito è riportato un esempio completo di download con gestione degli errori:
Web modular API
import { getStorage, ref, getDownloadURL } from "firebase/storage"; // Create a reference to the file we want to download const storage = getStorage(); const starsRef = ref(storage, 'images/stars.jpg'); // Get the download URL getDownloadURL(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-errors switch (error.code) { case 'storage/object-not-found': // File doesn't exist break; case 'storage/unauthorized': // User doesn't have permission to access the object break; case 'storage/canceled': // User canceled the upload break; // ... case 'storage/unknown': // Unknown error occurred, inspect the server response break; } });
Web namespaced API
// Create a reference to the file we want to download var starsRef = storageRef.child('images/stars.jpg'); // Get the download URL starsRef.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-errors switch (error.code) { case 'storage/object-not-found': // File doesn't exist break; case 'storage/unauthorized': // User doesn't have permission to access the object break; case 'storage/canceled': // User canceled the upload break; // ... case 'storage/unknown': // Unknown error occurred, inspect the server response break; } });
Puoi anche ottenere o aggiornare i metadati per i file archiviati in Cloud Storage.