Firebase için Cloud Storage, Firebase tarafından sağlanan ve yönetilen bir Cloud Storage paketinden dosyaları hızlı ve kolay bir şekilde indirmenize olanak tanır.
Referans Oluştur
Bir dosyayı indirmek için öncelikle indirmek istediğiniz dosyaya yönelik bir Cloud Storage referansı oluşturun .
Cloud Storage paketinizin köküne alt yollar ekleyerek bir referans oluşturabilir veya Cloud Storage'daki bir nesneye referans veren mevcut bir gs://
veya https://
URL'sinden bir referans oluşturabilirsiniz.
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');
URL aracılığıyla Verileri İndir
Bir Cloud Storage referansında getDownloadURL()
yöntemini çağırarak bir dosyanın indirme URL'sini alabilirsiniz.
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 });
Verileri Doğrudan SDK'dan İndirin
Sürüm 9.5 ve üzeri sürümlerden itibaren SDK, doğrudan indirme için şu işlevleri sağlar:
Bu işlevleri kullanarak, bir URL'den indirmeyi atlayabilir ve bunun yerine kodunuzdaki verileri döndürebilirsiniz. Bu, Firebase Güvenlik Kuralları aracılığıyla daha ayrıntılı erişim kontrolüne olanak tanır.
CORS Yapılandırması
Verileri doğrudan tarayıcıya indirmek için Cloud Storage paketinizi çapraz kaynaklara erişim (CORS) için yapılandırmanız gerekir. Bu, buradan yükleyebileceğiniz gsutil
komut satırı aracıyla yapılabilir.
Etki alanına dayalı herhangi bir kısıtlama istemiyorsanız (en yaygın senaryo), bu JSON'u cors.json
adlı bir dosyaya kopyalayın:
[ { "origin": ["*"], "method": ["GET"], "maxAgeSeconds": 3600 } ]
Bu kısıtlamaları dağıtmak için gsutil cors set cors.json gs://<your-cloud-storage-bucket>
çalıştırın.
Daha fazla bilgi için Google Bulut Depolama belgelerine bakın.
Hataları İşle
Dosyanın mevcut olmaması veya kullanıcının istenen dosyaya erişim iznine sahip olmaması da dahil olmak üzere indirme sırasında hataların ortaya çıkmasının çeşitli nedenleri vardır. Hatalarla ilgili daha fazla bilgiyi dokümanların Hataları İşleme bölümünde bulabilirsiniz.
Tam Örnek
Hata işlemeli bir indirmenin tam örneği aşağıda gösterilmektedir:
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; } });
Ayrıca Cloud Storage'da depolanan dosyalara ilişkin meta verileri alabilir veya güncelleyebilirsiniz .