Cloud Storage for Firebase umożliwia szybkie i łatwe pobieranie plików z Cloud Storage zasobnika udostępnianego i zarządzanego przez Firebase.
Tworzenie referencji
Aby pobrać plik, najpierw utwórz Cloud Storage referencję do pliku, który chcesz pobrać.
Referencję możesz utworzyć, dodając ścieżki podrzędne do katalogu głównego zasobnika
Cloud Storage lub utworzyć referencję na podstawie istniejącego adresu URL
gs:// lub https:// odwołującego się do obiektu w Cloud Storage.
Web
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
// 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');
Pobieranie danych za pomocą adresu URL
Adres URL pobierania pliku możesz uzyskać, wywołując metodę
getDownloadURL() na Cloud Storage referencji.
Web
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
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 });
Pobieranie danych bezpośrednio z pakietu SDK
Od wersji 9.5 pakiet SDK udostępnia te funkcje do bezpośredniego pobierania:
Za pomocą tych funkcji możesz pominąć pobieranie z adresu URL i zamiast tego zwrócić dane w kodzie. Umożliwia to bardziej szczegółową kontrolę dostępu za pomocą Firebase Security Rules.
Konfiguracja CORS
Aby pobierać dane bezpośrednio w przeglądarce, musisz skonfigurować swój
Cloud Storage zasobnik pod kątem dostępu między domenami (CORS). Możesz to zrobić
za pomocą narzędzia wiersza poleceń gsutil, które możesz
zainstalować tutaj.
Jeśli nie chcesz żadnych ograniczeń opartych na domenie (najczęstszy przypadek), skopiuj ten kod JSON do pliku o nazwie cors.json:
[
{
"origin": ["*"],
"method": ["GET"],
"maxAgeSeconds": 3600
}
]Aby wdrożyć
te ograniczenia, uruchom polecenie gsutil cors set cors.json gs://<your-cloud-storage-bucket>.
Więcej informacji znajdziesz w Google Cloud Storage dokumentacji.
Obsługa błędów
Błędy mogą występować podczas pobierania z wielu powodów, m.in. z powodu braku pliku lub braku uprawnień użytkownika do dostępu do żądanego pliku. Więcej informacji o błędach znajdziesz w sekcji Obsługa błędów w dokumentacji.
Pełny przykład
Poniżej znajdziesz pełny przykład pobierania z obsługą błędów:
Web
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
// 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; } });
Możesz też pobierać i aktualizować metadane plików przechowywanych w Cloud Storage.