Cloud Storage for Firebase ti consente di caricare file in modo rapido e semplice in un bucket Cloud Storage fornito e gestito da Firebase.
Caricare files
Per caricare un file su Cloud Storage, devi prima creare un riferimento al percorso completo del file, incluso il nome del file.
Web modular API
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 namespaced API
// 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
Carica da un Blob
o da File
Dopo aver creato un riferimento appropriato, chiami il metodo uploadBytes()
. uploadBytes()
accetta i file tramite le API JavaScript File e Blob e li carica su Cloud Storage.
Web modular API
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 namespaced API
// 'file' comes from the Blob or File API ref.put(file).then((snapshot) => { console.log('Uploaded a blob or file!'); });
Caricamento da un array di byte
Oltre ai tipi File
e Blob
, uploadBytes()
può anche caricare un Uint8Array
su Cloud Storage.
Web modular API
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 namespaced API
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!'); });
Carica da una stringa
Se un Blob
, File
o Uint8Array
non è disponibile, puoi utilizzare il metodo uploadString()
per caricare una stringa codificata raw, base64
, base64url
o data_url
su Cloud Storage.
Web modular API
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 namespaced API
// 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()
restituisce un UploadTask
, che puoi utilizzare come promessa o utilizzare per gestire e monitorare lo stato del caricamento.
Poiché il riferimento definisce il percorso completo del file, assicurati di eseguire il caricamento in un percorso non vuoto.
Aggiungi metadati del file
Quando carichi un file, puoi anche specificare i metadati per quel file. Questi metadati contengono proprietà tipiche dei metadati dei file come name
, size
e contentType
(comunemente indicato come tipo MIME). Cloud Storage deduce automaticamente il tipo di contenuto dall'estensione del file in cui il file è archiviato sul disco, ma se specifichi un contentType
nei metadati sovrascriverà il tipo rilevato automaticamente. Se non vengono specificati metadati contentType
e il file non ha un'estensione, Cloud Storage utilizza per impostazione predefinita il tipo application/octet-stream
. Maggiori informazioni sui metadati dei file sono disponibili nella sezione Utilizza metadati dei file .
Web modular API
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 namespaced API
// 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);
Gestisci caricamenti
Oltre ad avviare i caricamenti, puoi mettere in pausa, riprendere e annullare i caricamenti utilizzando i metodi pause()
, resume()
e cancel()
. La chiamata a pause()
o resume()
genererà pause
o cambiamenti di stato running
. La chiamata al metodo cancel()
comporta il fallimento del caricamento e la restituzione di un errore che indica che il caricamento è stato annullato.
Web modular API
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 namespaced API
// 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();
Monitorare l'avanzamento del caricamento
Durante il caricamento, l'attività di caricamento può generare eventi di avanzamento nell'osservatore state_changed
, come ad esempio:
Tipo di evento | Utilizzo tipico |
---|---|
running | Questo evento si attiva quando l'attività inizia o riprende il caricamento e viene spesso utilizzato insieme all'evento pause . Per caricamenti di dimensioni maggiori, questo evento potrebbe attivarsi più volte come aggiornamento dell'avanzamento. |
pause | Questo evento si attiva ogni volta che il caricamento viene messo in pausa e viene spesso utilizzato insieme all'evento running . |
Quando si verifica un evento, viene restituito un oggetto TaskSnapshot
. Questa istantanea è una visualizzazione immutabile dell'attività nel momento in cui si è verificato l'evento. Questo oggetto contiene le seguenti proprietà:
Proprietà | Tipo | Descrizione |
---|---|---|
bytesTransferred | Number | Il numero totale di byte trasferiti al momento dell'acquisizione di questo snapshot. |
totalBytes | Number | Il numero totale di byte previsti per il caricamento. |
state | firebase.storage.TaskState | Stato attuale del caricamento. |
metadata | firebaseStorage.Metadata | Prima del completamento del caricamento, i metadati vengono inviati al server. Al termine del caricamento, i metadati restituiti dal server. |
task | firebaseStorage.UploadTask | Si tratta di un'istantanea dell'attività, che può essere utilizzata per "mettere in pausa", "riprendere" o "annullare" l'attività. |
ref | firebaseStorage.Reference | Il riferimento da cui proviene questa attività. |
Questi cambiamenti di stato, combinati con le proprietà di TaskSnapshot
, forniscono un modo semplice ma potente per monitorare gli eventi di caricamento.
Web modular API
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 namespaced API
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); }); } );
Gestione degli errori
Esistono diversi motivi per cui potrebbero verificarsi errori durante il caricamento, incluso il file locale che non esiste o l'utente che non dispone dell'autorizzazione per caricare il file desiderato. Ulteriori informazioni sugli errori sono disponibili nella sezione Gestione degli errori della documentazione.
Esempio completo
Di seguito è riportato un esempio completo di caricamento con monitoraggio dell'avanzamento e gestione degli errori:
Web modular API
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 namespaced API
// 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); }); } );
Ora che hai caricato i file, impariamo come scaricarli da Cloud Storage.