Cloud Storage for Firebase können Sie schnell und einfach Dateien in einen Cloud Storage-Bucket hochladen, der von Firebase bereitgestellt und verwaltet wird.
Dateien hochladen
Wenn Sie eine Datei in Cloud Storage hochladen möchten, erstellen Sie zuerst einen Verweis auf den vollständigen Pfad der Datei, einschließlich des Dateinamens.
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
Aus einem Blob oder einer File hochladen
Nachdem Sie einen entsprechenden Verweis erstellt haben, rufen Sie die Methode uploadBytes() auf. uploadBytes() verwendet Dateien über die JavaScript
File und
Blob-APIs und lädt
sie in Cloud Storage hoch.
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!'); });
Aus einem Byte-Array hochladen
Neben den Typen File und Blob kann uploadBytes() auch ein
Uint8Array in Cloud Storage hochladen.
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!'); });
Aus einem String hochladen
Wenn kein Blob, keine File oder kein Uint8Array verfügbar ist, können Sie mit der Methode
uploadString() einen unformatierten, base64, base64url oder data_url
codierten String in Cloud Storage hochladen.
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!'); });
Da der Verweis den vollständigen Pfad zur Datei definiert, müssen Sie darauf achten, dass Sie in einen nicht leeren Pfad hochladen.
Dateimetadaten hinzufügen
Beim Hochladen einer Datei können Sie auch Metadaten für diese Datei angeben.
Diese Metadaten enthalten typische Dateimetadaten-Attribute wie name, size und contentType (allgemein als MIME-Typ bezeichnet). Cloud Storage
leitet den Inhaltstyp automatisch aus der Dateierweiterung ab, wenn die Datei auf der Festplatte
gespeichert ist. Wenn Sie jedoch in den Metadaten einen contentType angeben, wird der automatisch erkannte Typ
überschrieben. Wenn keine contentType-Metadaten angegeben sind und
die Datei keine Dateierweiterung hat, verwendet Cloud Storage standardmäßig den
Typ application/octet-stream. Weitere Informationen zu Dateimetadaten finden Sie
im Abschnitt Dateimetadaten verwenden.
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);
Uploads verwalten
Neben dem Starten von Uploads können Sie Uploads mit den Methoden pause(), resume() und cancel() auch pausieren, fortsetzen und abbrechen. Wenn Sie pause() oder
resume() aufrufen, werden Änderungen des Status pause oder running ausgelöst. Wenn Sie die Methode cancel() aufrufen, schlägt der Upload fehl und es wird ein Fehler zurückgegeben, der angibt, dass der Upload abgebrochen wurde.
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();
Upload-Fortschritt beobachten
Während des Uploads kann die Upload-Aufgabe im Observer state_changed Fortschrittsereignisse auslösen, z. B.:
| Ereignistyp | Typische Verwendung |
|---|---|
running |
Dieses Ereignis wird ausgelöst, wenn die Aufgabe mit dem Hochladen beginnt oder es fortsetzt. Es wird häufig
in Verbindung mit dem pause Ereignis verwendet. Bei größeren
Uploads kann dieses Ereignis mehrmals als Fortschrittsaktualisierung ausgelöst werden. |
pause |
Dieses Ereignis wird jedes Mal ausgelöst, wenn der Upload pausiert wird. Es wird häufig in
Verbindung mit dem running Ereignis verwendet. |
Wenn ein Ereignis eintritt, wird ein TaskSnapshot-Objekt zurückgegeben. Dieser Snapshot ist eine unveränderliche Ansicht der Aufgabe zum Zeitpunkt des Ereignisses.
Dieses Objekt enthält die folgenden Attribute:
| Attribut | Typ | Beschreibung |
|---|---|---|
bytesTransferred |
Number |
Die Gesamtzahl der Byte, die übertragen wurden, als dieser Snapshot aufgenommen wurde. |
totalBytes |
Number |
Die Gesamtzahl der Byte, die hochgeladen werden sollen. |
state |
firebase.storage.TaskState |
Aktueller Status des Uploads. |
metadata |
firebaseStorage.Metadata |
Vor Abschluss des Uploads die Metadaten, die an den Server gesendet wurden. Nach Abschluss des Uploads die Metadaten, die der Server zurückgesendet hat. |
task |
firebaseStorage.UploadTask |
Die Aufgabe, von der dieser Snapshot stammt. Sie kann verwendet werden, um die Aufgabe zu `pause`, `resume` oder `cancel`. |
ref |
firebaseStorage.Reference |
Der Verweis, aus dem diese Aufgabe stammt. |
Diese Statusänderungen in Kombination mit den Attributen von TaskSnapshot bieten eine einfache, aber leistungsstarke Möglichkeit, Upload-Ereignisse zu beobachten.
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); }); } );
Fehlerbehandlung
Es gibt eine Reihe von Gründen, warum beim Upload Fehler auftreten können. Dazu gehören beispielsweise, dass die lokale Datei nicht vorhanden ist oder der Nutzer keine Berechtigung zum Hochladen der gewünschten Datei hat. Weitere Informationen zu Fehlern finden Sie im Abschnitt Fehler behandeln in der Dokumentation.
Vollständiges Beispiel
Ein vollständiges Beispiel für einen Upload mit Fortschrittsbeobachtung und Fehlerbehandlung finden Sie unten:
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); }); } );
Nachdem Sie nun Dateien hochgeladen haben, erfahren Sie, wie Sie sie herunterladen aus Cloud Storage.