Cloud Storage for Firebase, Firebase tarafından sağlanan ve yönetilen bir Cloud Storage paketine dosyaları hızlı ve kolay bir şekilde yüklemenize olanak tanır.
Dosya Yükle
Cloud Storage'ya dosya yüklemek için önce dosya adı da dahil olmak üzere dosyanın tam yoluna referans oluşturursunuz.
Web
import { getStorage, ref } from "firebase/storage"; // Create a root reference const storage = getStorage(); // Create a reference to 'mountains.jpg' const mountainsRef = ref(storage, 'mountains.jpg'); // Create a reference to 'images/mountains.jpg' const mountainImagesRef = ref(storage, 'images/mountains.jpg'); // While the file names are the same, the references point to different files mountainsRef.name === mountainImagesRef.name; // true mountainsRef.fullPath === mountainImagesRef.fullPath; // false
Web
// Create a root reference var storageRef = firebase.storage().ref(); // Create a reference to 'mountains.jpg' var mountainsRef = storageRef.child('mountains.jpg'); // Create a reference to 'images/mountains.jpg' var mountainImagesRef = storageRef.child('images/mountains.jpg'); // While the file names are the same, the references point to different files mountainsRef.name === mountainImagesRef.name; // true mountainsRef.fullPath === mountainImagesRef.fullPath; // false
Blob
veya File
üzerinden yükleme
Uygun bir referans oluşturduktan sonra uploadBytes()
yöntemini çağırırsınız. uploadBytes()
, JavaScript File ve Blob API'leri aracılığıyla dosyaları alır ve Cloud Storage'a yükler.
Web
import { getStorage, ref, uploadBytes } from "firebase/storage"; const storage = getStorage(); const storageRef = ref(storage, 'some-child'); // 'file' comes from the Blob or File API uploadBytes(storageRef, file).then((snapshot) => { console.log('Uploaded a blob or file!'); });
Web
// 'file' comes from the Blob or File API ref.put(file).then((snapshot) => { console.log('Uploaded a blob or file!'); });
Byte dizisinden yükleme
File
ve Blob
türlerine ek olarak uploadBytes()
, Cloud Storage'e Uint8Array
de yükleyebilir.
Web
import { getStorage, ref, uploadBytes } from "firebase/storage"; const storage = getStorage(); const storageRef = ref(storage, 'some-child'); const bytes = new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x21]); uploadBytes(storageRef, bytes).then((snapshot) => { console.log('Uploaded an array!'); });
Web
var bytes = new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x21]); ref.put(bytes).then((snapshot) => { console.log('Uploaded an array!'); });
Dizeden yükleme
Blob
, File
veya Uint8Array
kullanılamıyorsa uploadString()
yöntemini kullanarak base64
, base64url
veya data_url
kodlu bir dizeyi Cloud Storage'ye yükleyebilirsiniz.
Web
import { getStorage, ref, uploadString } from "firebase/storage"; const storage = getStorage(); const storageRef = ref(storage, 'some-child'); // Raw string is the default if no format is provided const message = 'This is my message.'; uploadString(storageRef, message).then((snapshot) => { console.log('Uploaded a raw string!'); }); // Base64 formatted string const message2 = '5b6p5Y+344GX44G+44GX44Gf77yB44GK44KB44Gn44Go44GG77yB'; uploadString(storageRef, message2, 'base64').then((snapshot) => { console.log('Uploaded a base64 string!'); }); // Base64url formatted string const message3 = '5b6p5Y-344GX44G-44GX44Gf77yB44GK44KB44Gn44Go44GG77yB'; uploadString(storageRef, message3, 'base64url').then((snapshot) => { console.log('Uploaded a base64url string!'); }); // Data URL string const message4 = 'data:text/plain;base64,5b6p5Y+344GX44G+44GX44Gf77yB44GK44KB44Gn44Go44GG77yB'; uploadString(storageRef, message4, 'data_url').then((snapshot) => { console.log('Uploaded a data_url string!'); });
Web
// Raw string is the default if no format is provided var message = 'This is my message.'; ref.putString(message).then((snapshot) => { console.log('Uploaded a raw string!'); }); // Base64 formatted string var message = '5b6p5Y+344GX44G+44GX44Gf77yB44GK44KB44Gn44Go44GG77yB'; ref.putString(message, 'base64').then((snapshot) => { console.log('Uploaded a base64 string!'); }); // Base64url formatted string var message = '5b6p5Y-344GX44G-44GX44Gf77yB44GK44KB44Gn44Go44GG77yB'; ref.putString(message, 'base64url').then((snapshot) => { console.log('Uploaded a base64url string!'); }); // Data URL string var message = 'data:text/plain;base64,5b6p5Y+344GX44G+44GX44Gf77yB44GK44KB44Gn44Go44GG77yB'; ref.putString(message, 'data_url').then((snapshot) => { console.log('Uploaded a data_url string!'); });
Referans, dosyanın tam yolunu tanımladığından boş olmayan bir yola yükleme yaptığınızdan emin olun.
Dosya meta verileri ekleme
Dosya yüklerken bu dosyanın meta verilerini de belirtebilirsiniz.
Bu meta veriler, name
, size
ve contentType
(genellikle MIME türü olarak adlandırılır) gibi tipik dosya meta veri özelliklerini içerir. Cloud Storage
Dosyanın diskte depolandığı yerdeki dosya uzantısından içerik türünü otomatik olarak çıkarır ancak meta verilerde contentType
belirtirseniz otomatik olarak algılanan türü geçersiz kılar. contentType
meta verisi belirtilmemişse ve dosyanın dosya uzantısı yoksa Cloud Storage varsayılan olarak application/octet-stream
türü olur. Dosya meta verileri hakkında daha fazla bilgiyi Dosya Meta Verilerini Kullanma bölümünde bulabilirsiniz.
Web
import { getStorage, ref, uploadBytes } from "firebase/storage"; const storage = getStorage(); const storageRef = ref(storage, 'images/mountains.jpg'); // Create file metadata including the content type /** @type {any} */ const metadata = { contentType: 'image/jpeg', }; // Upload the file and metadata const uploadTask = uploadBytes(storageRef, file, metadata);
Web
// Create file metadata including the content type var metadata = { contentType: 'image/jpeg', }; // Upload the file and metadata var uploadTask = storageRef.child('images/mountains.jpg').put(file, metadata);
Yüklemeleri Yönet
Yüklemeleri başlatmanın yanı sıra pause()
, resume()
ve cancel()
yöntemlerini kullanarak yüklemeleri duraklatabilir, devam ettirebilir ve iptal edebilirsiniz. pause()
veya
resume()
işlevi çağrıldığında pause
veya running
durum değişiklikleri tetiklenir. cancel()
yönteminin çağrılması, yüklemenin başarısız olmasına ve yüklemenin iptal edildiğini belirten bir hata döndürmesine neden olur.
Web
import { getStorage, ref, uploadBytesResumable } from "firebase/storage"; const storage = getStorage(); const storageRef = ref(storage, 'images/mountains.jpg'); // Upload the file and metadata const uploadTask = uploadBytesResumable(storageRef, file); // Pause the upload uploadTask.pause(); // Resume the upload uploadTask.resume(); // Cancel the upload uploadTask.cancel();
Web
// Upload the file and metadata var uploadTask = storageRef.child('images/mountains.jpg').put(file); // Pause the upload uploadTask.pause(); // Resume the upload uploadTask.resume(); // Cancel the upload uploadTask.cancel();
Yükleme ilerleme durumunu izleme
Yükleme sırasında, yükleme görevi state_changed
gözlemcisinde aşağıdaki gibi ilerleme etkinlikleri oluşturabilir:
Etkinlik Türü | Tipik Kullanım |
---|---|
running |
Bu etkinlik, görev başlatıldığında veya yükleme devam ettirildiğinde tetiklenir ve genellikle pause etkinliğiyle birlikte kullanılır. Daha büyük yüklemelerde bu etkinlik, ilerleme durumu güncellemesi olarak birden fazla kez tetiklenebilir. |
pause |
Bu etkinlik, yükleme her duraklatıldığında tetiklenir ve genellikle running etkinliğiyle birlikte kullanılır. |
Bir etkinlik gerçekleştiğinde TaskSnapshot
nesnesi geri iletilir. Bu anlık görüntü, etkinlik gerçekleştiği sırada görevle ilgili değişmez bir görünüm sunar.
Bu nesne aşağıdaki özellikleri içerir:
Özellik | Tür | Açıklama |
---|---|---|
bytesTransferred |
Number |
Bu anlık görüntü alındığında aktarılan toplam bayt sayısı. |
totalBytes |
Number |
Yüklenecek toplam bayt sayısı. |
state |
firebase.storage.TaskState |
Yüklemenin mevcut durumu. |
metadata |
firebaseStorage.Metadata |
Yükleme tamamlanmadan önce sunucuya gönderilen meta veriler. Yükleme tamamlandıktan sonra sunucunun geri gönderdiği meta veriler. |
task |
firebaseStorage.UploadTask |
Bu, görevin anlık görüntüsüdür. Bu anlık görüntü, görevi `duraklatmak`, `devam ettirmek` veya `iptal etmek` için kullanılabilir. |
ref |
firebaseStorage.Reference |
Bu görevin geldiği referans. |
Durumdaki bu değişiklikler, TaskSnapshot
özellikleriyle birlikte yükleme etkinliklerini izlemenin basit ancak etkili bir yolunu sunar.
Web
import { getStorage, ref, uploadBytesResumable, getDownloadURL } from "firebase/storage"; const storage = getStorage(); const storageRef = ref(storage, 'images/rivers.jpg'); const uploadTask = uploadBytesResumable(storageRef, file); // Register three observers: // 1. 'state_changed' observer, called any time the state changes // 2. Error observer, called on failure // 3. Completion observer, called on successful completion uploadTask.on('state_changed', (snapshot) => { // Observe state change events such as progress, pause, and resume // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100; console.log('Upload is ' + progress + '% done'); switch (snapshot.state) { case 'paused': console.log('Upload is paused'); break; case 'running': console.log('Upload is running'); break; } }, (error) => { // Handle unsuccessful uploads }, () => { // Handle successful uploads on complete // For instance, get the download URL: https://firebasestorage.googleapis.com/... getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => { console.log('File available at', downloadURL); }); } );
Web
var uploadTask = storageRef.child('images/rivers.jpg').put(file); // Register three observers: // 1. 'state_changed' observer, called any time the state changes // 2. Error observer, called on failure // 3. Completion observer, called on successful completion uploadTask.on('state_changed', (snapshot) => { // Observe state change events such as progress, pause, and resume // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100; console.log('Upload is ' + progress + '% done'); switch (snapshot.state) { case firebase.storage.TaskState.PAUSED: // or 'paused' console.log('Upload is paused'); break; case firebase.storage.TaskState.RUNNING: // or 'running' console.log('Upload is running'); break; } }, (error) => { // Handle unsuccessful uploads }, () => { // Handle successful uploads on complete // For instance, get the download URL: https://firebasestorage.googleapis.com/... uploadTask.snapshot.ref.getDownloadURL().then((downloadURL) => { console.log('File available at', downloadURL); }); } );
Hata İşleme
Yükleme sırasında hataların oluşmasının çeşitli nedenleri vardır. Örneğin, yerel dosya mevcut olmayabilir veya kullanıcının istenen dosyayı yükleme izni olmayabilir. Hatalar hakkında daha fazla bilgiyi dokümanların Hataları İşleme bölümünde bulabilirsiniz.
Tam Örnek
Aşağıda, ilerleme izleme ve hata işleme içeren bir yükleme işleminin tam örneği gösterilmektedir:
Web
import { getStorage, ref, uploadBytesResumable, getDownloadURL } from "firebase/storage"; const storage = getStorage(); // Create the file metadata /** @type {any} */ const metadata = { contentType: 'image/jpeg' }; // Upload file and metadata to the object 'images/mountains.jpg' const storageRef = ref(storage, 'images/' + file.name); const uploadTask = uploadBytesResumable(storageRef, file, metadata); // Listen for state changes, errors, and completion of the upload. uploadTask.on('state_changed', (snapshot) => { // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100; console.log('Upload is ' + progress + '% done'); switch (snapshot.state) { case 'paused': console.log('Upload is paused'); break; case 'running': console.log('Upload is running'); break; } }, (error) => { // A full list of error codes is available at // https://firebase.google.com/docs/storage/web/handle-errors switch (error.code) { 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 error.serverResponse break; } }, () => { // Upload completed successfully, now we can get the download URL getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => { console.log('File available at', downloadURL); }); } );
Web
// Create the file metadata var metadata = { contentType: 'image/jpeg' }; // Upload file and metadata to the object 'images/mountains.jpg' var uploadTask = storageRef.child('images/' + file.name).put(file, metadata); // Listen for state changes, errors, and completion of the upload. uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed' (snapshot) => { // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100; console.log('Upload is ' + progress + '% done'); switch (snapshot.state) { case firebase.storage.TaskState.PAUSED: // or 'paused' console.log('Upload is paused'); break; case firebase.storage.TaskState.RUNNING: // or 'running' console.log('Upload is running'); break; } }, (error) => { // A full list of error codes is available at // https://firebase.google.com/docs/storage/web/handle-errors switch (error.code) { 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 error.serverResponse break; } }, () => { // Upload completed successfully, now we can get the download URL uploadTask.snapshot.ref.getDownloadURL().then((downloadURL) => { console.log('File available at', downloadURL); }); } );
Dosyaları yüklediğinize göre şimdi Cloud Storage'dan nasıl indireceğinizi öğrenelim.