Cloud Storage for Firebase позволяет быстро и легко загружать файлы в хранилище Cloud Storage предоставляемое и управляемое Firebase.
Загрузка файлов
Для загрузки файла в Cloud Storage необходимо сначала создать ссылку на полный путь к файлу, включая его имя.
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
Загрузка из двоичных File или Blob -объектов.
После создания соответствующей ссылки необходимо вызвать метод uploadBytes() . Метод uploadBytes() принимает файлы через API файлов и BLOB-объектов JavaScript и загружает их в Cloud Storage .
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!'); });
Загрузка из массива байтов
Помимо типов File и Blob , uploadBytes() также может загружать в Cloud Storage массивы типа Uint8Array .
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!'); });
Загрузка из строки
Если объект Blob , File или Uint8Array недоступен, вы можете использовать метод uploadString() для загрузки в Cloud Storage строки в необработанном виде, в формате base64 , base64url или data_url .
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!'); });
Поскольку в ссылке указан полный путь к файлу, убедитесь, что вы загружаете его в непустой путь.
Добавить метаданные файла
При загрузке файла вы также можете указать для него метаданные. Эти метаданные содержат типичные свойства метаданных файла, такие как name , size и contentType (обычно называемый MIME-типом). Cloud Storage автоматически определяет тип содержимого по расширению файла, в котором он хранится на диске, но если вы укажете contentType в метаданных, он переопределит автоматически определенный тип. Если метаданные contentType не указаны и у файла нет расширения, Cloud Storage по умолчанию использует тип application/octet-stream . Дополнительную информацию о метаданных файлов можно найти в разделе «Использование метаданных файлов» .
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);
Управление загрузками
Помимо начала загрузки, вы можете приостанавливать, возобновлять и отменять загрузку с помощью методов pause() , resume() и cancel() . Вызов pause() или resume() вызовет изменение состояния pause или running . Вызов метода cancel() приведет к сбою загрузки и возврату ошибки, указывающей на отмену загрузки.
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();
Отслеживание хода загрузки
В процессе загрузки задача загрузки может генерировать события прогресса в наблюдателе state_changed , например:
| Тип события | Типичное использование |
|---|---|
running | Это событие срабатывает при начале или возобновлении загрузки задачи и часто используется в сочетании с событием pause . Для больших объемов загрузки это событие может срабатывать несколько раз в качестве обновления информации о ходе выполнения. |
pause | Это событие срабатывает всякий раз, когда загрузка приостанавливается, и часто используется в сочетании с событием running . |
При возникновении события возвращается объект TaskSnapshot . Этот снимок представляет собой неизменяемое представление задачи на момент возникновения события. Объект содержит следующие свойства:
| Свойство | Тип | Описание |
|---|---|---|
bytesTransferred | Number | Общее количество байтов, переданных на момент создания этого снимка. |
totalBytes | Number | Общее количество байтов, которые планируется загрузить. |
state | firebase.storage.TaskState | Текущее состояние загрузки. |
metadata | firebaseStorage.Metadata | Перед завершением загрузки метаданные отправляются на сервер. После завершения загрузки метаданные отправляются сервером обратно. |
task | firebaseStorage.UploadTask | Это снимок задачи, который можно использовать для ее приостановки, возобновления или отмены. |
ref | firebaseStorage.Reference | Источник, послуживший основанием для данного задания. |
Эти изменения состояния в сочетании со свойствами TaskSnapshot обеспечивают простой, но мощный способ отслеживания событий загрузки.
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); }); } );
Обработка ошибок
При загрузке могут возникать ошибки по ряду причин, включая отсутствие локального файла или отсутствие у пользователя разрешения на загрузку нужного файла. Более подробную информацию об ошибках можно найти в разделе «Обработка ошибок» документации.
Полный пример
Полный пример загрузки с отслеживанием хода процесса и обработкой ошибок показан ниже:
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); }); } );
Теперь, когда вы загрузили файлы, давайте узнаем, как их скачать из Cloud Storage .