فایل‌ها را با فضای ذخیره‌سازی ابری در وب آپلود کنید

Cloud Storage for Firebase به شما این امکان را می دهد که به سرعت و به راحتی فایل ها را در یک سطل Cloud Storage که توسط Firebase تهیه و مدیریت می شود آپلود کنید.

آپلود فایل ها

برای آپلود یک فایل در Cloud Storage، ابتدا یک مرجع به مسیر کامل فایل، از جمله نام فایل ایجاد می کنید.

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 

از یک Blob یا File آپلود کنید

هنگامی که یک مرجع مناسب ایجاد کردید، سپس متد uploadBytes() فراخوانی می کنید. uploadBytes() فایلها را از طریق فایل جاوا اسکریپت و APIهای Blob می گیرد و آنها را در فضای ذخیره سازی ابری آپلود می کند.

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!');
});

آپلود از آرایه بایت

علاوه بر انواع File و Blob ، uploadBytes() همچنین می تواند Uint8Array در فضای ذخیره سازی ابری آپلود کند.

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!');
});

آپلود از یک رشته

اگر Blob ، File یا Uint8Array در دسترس نیست، می‌توانید از متد uploadString() برای آپلود یک رشته رمزگذاری‌شده خام، base64 ، base64url یا data_url در فضای ذخیره‌سازی ابری استفاده کنید.

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!');
});

از آنجایی که مرجع مسیر کامل فایل را مشخص می کند، مطمئن شوید که در مسیری غیر خالی آپلود می کنید.

افزودن فراداده فایل

هنگام آپلود یک فایل، می توانید متادیتای آن فایل را نیز مشخص کنید. این ابرداده حاوی ویژگی‌های فراداده معمولی فایل مانند name ، size و contentType (که معمولاً به عنوان نوع MIME شناخته می‌شود) است. Cloud Storage به طور خودکار نوع محتوا را از پسوند فایلی که فایل روی دیسک ذخیره می شود استنتاج می کند، اما اگر یک contentType در فراداده مشخص کنید، نوع شناسایی خودکار را لغو می کند. اگر هیچ متادیتا contentType مشخص نشده باشد و فایل پسوند فایلی نداشته باشد، Cloud Storage به طور پیش‌فرض روی نوع application/octet-stream قرار می‌گیرد. اطلاعات بیشتر در مورد فراداده فایل را می توانید در بخش Use File Metadata بیابید.

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);

مدیریت آپلودها

علاوه بر شروع آپلود، می توانید با استفاده از متدهای pause pause() , resume() و cancel() آپلودها را مکث، از سرگیری و لغو کنید. فراخوانی pause() یا resume() باعث افزایش pause یا running تغییرات حالت می شود. فراخوانی متد cancel() باعث می شود که آپلود با شکست مواجه شود و خطایی نشان دهد که آپلود لغو شده است.

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();

نظارت بر پیشرفت آپلود

در حین آپلود، وظیفه آپلود ممکن است رویدادهای پیشرفت را در ناظر 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 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);
    });
  }
);

رسیدگی به خطا

دلایل متعددی وجود دارد که ممکن است هنگام آپلود خطا رخ دهد، از جمله اینکه فایل محلی موجود نیست یا کاربر مجوز آپلود فایل مورد نظر را ندارد. اطلاعات بیشتر در مورد خطاها را می توانید در بخش Handle Errors در اسناد پیدا کنید.

مثال کامل

یک مثال کامل از آپلود با نظارت بر پیشرفت و مدیریت خطا در زیر نشان داده شده است:

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);
    });
  }
);

اکنون که فایل‌ها را آپلود کردید، بیایید نحوه دانلود آنها را از فضای ذخیره‌سازی ابری بیاموزیم.