این صفحه نحوه استفاده از Cloud Storage for Firebase SDK را برای بارگذاری فایلها در یک دسته Cloud Storage شرح میدهد.
برای اطلاعات بیشتر، این پرسشگان را ببینید.
بارگذاری فایلها
برای بارگذاری فایل در 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
بارگذاری از Blob یا File
پساز ایجاد مرجع مناسب، میتوانید روش
uploadBytes() را فراخوانی کنید. uploadBytes() فایلها را ازطریق میاناهای برنامهسازی کاربردی
File و
Blob جاوا اسکریپت
دریافت میکند و سپس آنها را در 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() همچنین میتواند
Uint8Array را در Cloud Storage بارگذاری کند.
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() برای بارگذاری رشته کدبندیشده خام، base64، base64url، یا data_url
در Cloud Storage استفاده کنید.
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
بهطور خودکار نوع MIME را از پسوند فایل در جایی که فایل در دیسک ذخیره شده است استنباط میکند، اما اگر 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 آشنا شوید.