Cloud Storage dla Firebase umożliwia szybkie i łatwe przesyłanie plików do zasobnika Cloud Storage udostępnianego i zarządzanego przez Firebase.
Prześlij pliki
Aby przesłać plik do Cloud Storage, najpierw utwórz odniesienie do pełnej ścieżki pliku, w tym nazwy pliku.
Web version 9
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 version 8
// 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
Przekaż z obiektu Blob
lub File
Po utworzeniu odpowiedniego odniesienia wywołujesz metodę uploadBytes()
. uploadBytes()
pobiera pliki za pośrednictwem API JavaScript File i Blob i przesyła je do Cloud Storage.
Web version 9
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 version 8
// 'file' comes from the Blob or File API ref.put(file).then((snapshot) => { console.log('Uploaded a blob or file!'); });
Prześlij z tablicy bajtów
Oprócz typów File
i Blob
, uploadBytes()
może również przesyłać Uint8Array
do Cloud Storage.
Web version 9
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 version 8
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!'); });
Prześlij z ciągu
Jeśli Blob
, File
lub Uint8Array
nie jest dostępny, możesz użyć metody uploadString()
w celu przesłania ciągu zakodowanego w formacie raw, base64
, base64url
lub data_url
do Cloud Storage.
Web version 9
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 version 8
// 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!'); });
uploadString()
zwraca UploadTask
, którego możesz użyć jako obietnicy lub użyć do zarządzania i monitorowania statusu przesyłania.
Ponieważ odwołanie określa pełną ścieżkę do pliku, upewnij się, że przesyłasz do niepustej ścieżki.
Dodaj metadane pliku
Przesyłając plik, możesz także określić jego metadane. Te metadane zawierają typowe właściwości metadanych pliku, takie jak name
, size
i contentType
(powszechnie określane jako typ MIME). Cloud Storage automatycznie określa typ zawartości na podstawie rozszerzenia pliku, w którym plik jest przechowywany na dysku, ale jeśli określisz contentType
w metadanych, zastąpi on automatycznie wykryty typ. Jeśli nie określono metadanych contentType
, a plik nie ma rozszerzenia, Cloud Storage domyślnie przyjmuje typ application/octet-stream
. Więcej informacji na temat metadanych plików można znaleźć w sekcji Korzystanie z metadanych plików .
Web version 9
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 version 8
// 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);
Zarządzaj przesyłaniem
Oprócz rozpoczynania przesyłania możesz wstrzymywać, wznawiać i anulować przesyłanie za pomocą metod pause()
, resume()
i cancel()
. Wywołanie pause()
lub resume()
wywoła pause
lub running
zmiany stanu. Wywołanie metody cancel()
skutkuje niepowodzeniem przesyłania i zwróceniem błędu wskazującego, że przesyłanie zostało anulowane.
Web version 9
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 version 8
// 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();
Monitoruj postęp przesyłania
Podczas przesyłania zadanie przesyłania może wywołać zdarzenia postępu w obserwatorze state_changed
, takie jak:
Typ wydarzenia | Typowe użycie |
---|---|
running | To zdarzenie jest uruchamiane, gdy zadanie rozpoczyna się lub wznawia przesyłanie i jest często używane w połączeniu ze zdarzeniem pause . W przypadku przesyłania większych plików to zdarzenie może zostać uruchomione wiele razy w ramach aktualizacji postępu. |
pause | To zdarzenie jest uruchamiane za każdym razem, gdy przesyłanie jest wstrzymane, i jest często używane w połączeniu ze zdarzeniem running . |
Gdy wystąpi zdarzenie, obiekt TaskSnapshot
jest przekazywany z powrotem. Ta migawka jest niezmiennym widokiem zadania w momencie wystąpienia zdarzenia. Ten obiekt zawiera następujące właściwości:
Nieruchomość | Typ | Opis |
---|---|---|
bytesTransferred | Number | Łączna liczba bajtów, które zostały przesłane podczas wykonywania tej migawki. |
totalBytes | Number | Całkowita liczba bajtów, które mają zostać przesłane. |
state | firebase.storage.TaskState | Bieżący stan przesyłania. |
metadata | firebaseStorage.Metadata | Przed zakończeniem przesyłania metadane są wysyłane na serwer. Po zakończeniu przesyłania metadane odesłane przez serwer. |
task | firebaseStorage.UploadTask | Zadanie, którego jest to migawka, którego można użyć do „wstrzymania”, „wznowienia” lub „anulowania” zadania. |
ref | firebaseStorage.Reference | Odniesienie, z którego pochodzi to zadanie. |
Te zmiany stanu w połączeniu z właściwościami TaskSnapshot
zapewniają prosty, ale skuteczny sposób monitorowania zdarzeń przesyłania.
Web version 9
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 version 8
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); }); } );
Obsługa błędów
Istnieje wiele powodów, dla których mogą wystąpić błędy podczas przesyłania, w tym brak pliku lokalnego lub brak uprawnień użytkownika do przesłania żądanego pliku. Więcej informacji na temat błędów można znaleźć w sekcji Obsługa błędów w dokumentacji.
Pełny przykład
Poniżej przedstawiono pełny przykład przesyłania z monitorowaniem postępu i obsługą błędów:
Web version 9
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 version 8
// 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); }); } );
Po przesłaniu plików dowiedzmy się, jak pobrać je z Cloud Storage.