بارگیری کردن فایل‌ها با Cloud Storage در وب

این صفحه نحوه استفاده از کیت توسعه نرم‌افزار Cloud Storage for Firebase را برای بارگیری فایل‌ها از یک دسته Cloud Storage شرح می‌دهد.

ایجاد مرجع

برای بارگیری فایل، ابتدا یک Cloud Storage مرجع به فایلی که می‌خواهید بارگیری کنید ایجاد کنید.

می‌توانید با افزودن مسیرهای فرزند به ریشه Cloud Storage bucket، مرجع ایجاد کنید یا می‌توانید از نشانی وب gs:// یا https:// موجود که به شیئی در Cloud Storage ارجاع می‌دهد، مرجع ایجاد کنید.

Web

import { getStorage, ref } from "firebase/storage";

// Create a reference with an initial file path and name
const storage = getStorage();
const pathReference = ref(storage, 'images/stars.jpg');

// Create a reference from a Google Cloud Storage URI
const gsReference = ref(storage, 'gs://bucket/images/stars.jpg');

// Create a reference from an HTTPS URL
// Note that in the URL, characters are URL escaped!
const httpsReference = ref(storage, 'https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg');  

Web

// Create a reference with an initial file path and name
var storage = firebase.storage();
var pathReference = storage.ref('images/stars.jpg');

// Create a reference from a Google Cloud Storage URI
var gsReference = storage.refFromURL('gs://bucket/images/stars.jpg');

// Create a reference from an HTTPS URL
// Note that in the URL, characters are URL escaped!
var httpsReference = storage.refFromURL('https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg');  

بارگیری داده ازطریق نشانی وب

با فراخوانی روش getDownloadURL() در مرجع Cloud Storage می‌توانید نشانی وب بارگیری را برای فایل دریافت کنید.

Web

import { getStorage, ref, getDownloadURL } from "firebase/storage";

const storage = getStorage();
const starsRef = ref(storage, 'images/stars.jpg');

getDownloadURL(starsRef)
  .then((url) => {
    // `url` is the download URL for 'images/stars.jpg'

    // This can be downloaded directly:
    const xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = (event) => {
      const blob = xhr.response;
    };
    xhr.open('GET', url);
    xhr.send();

    // Or inserted into an <img> element
    const img = document.getElementById('myimg');
    img.setAttribute('src', url);
  })
  .catch((error) => {
    // Handle any errors
  });

Web

storageRef.child('images/stars.jpg').getDownloadURL()
  .then((url) => {
    // `url` is the download URL for 'images/stars.jpg'

    // This can be downloaded directly:
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = (event) => {
      var blob = xhr.response;
    };
    xhr.open('GET', url);
    xhr.send();

    // Or inserted into an <img> element
    var img = document.getElementById('myimg');
    img.setAttribute('src', url);
  })
  .catch((error) => {
    // Handle any errors
  });

بارگیری داده‌ها مستقیماً از کیت توسعه نرم‌افزار

از نسخه ۹.۵ و بالاتر، کیت توسعه نرم‌افزار این توابع را برای بارگیری مستقیم ارائه می‌دهد:

بااستفاده از این تابع‌ها، می‌توانید بارگیری از نشانی وب را دور بزنید و درعوض داده‌ها را در کدتان برگردانید. این کار امکان کنترل دسترسی دقیق‌تر را ازطریق Firebase Security Rules فراهم می‌کند.

پیکربندی CORS

برای بارگیری مستقیم داده‌ها در مرورگر، باید Cloud Storage bucket را برای دسترسی میان‌مبدئی (CORS) پیکربندی کنید. این کار را می‌توان با ابزار خط فرمان gsutil انجام داد که می‌توانید آن را از اینجا نصب کنید.

اگر نمی‌خواهید هیچ محدودیت مبتنی بر دامنه‌ای داشته باشید (رایج‌ترین سناریو)، این JSON را در فایلی با نام cors.json کپی کنید:

[
  {
    "origin": ["*"],
    "method": ["GET"],
    "maxAgeSeconds": 3600
  }
]

برای اعمال این محدودیت‌ها، gsutil cors set cors.json gs://<your-cloud-storage-bucket> را اجرا کنید.

برای اطلاعات بیشتر، به Google Cloud Storage اسناد مراجعه کنید.

مدیریت کردن خطا

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

نمونه کامل

نمونه کاملی از بارگیری با رسیدگی به خطا در زیر نشان داده شده است:

Web

import { getStorage, ref, getDownloadURL } from "firebase/storage";

// Create a reference to the file we want to download
const storage = getStorage();
const starsRef = ref(storage, 'images/stars.jpg');

// Get the download URL
getDownloadURL(starsRef)
  .then((url) => {
    // Insert url into an <img> tag to "download"
  })
  .catch((error) => {
    // A full list of error codes is available at
    // https://firebase.google.com/docs/storage/web/handle-errors
    switch (error.code) {
      case 'storage/object-not-found':
        // File doesn't exist
        break;
      case 'storage/unauthorized':
        // User doesn't have permission to access the object
        break;
      case 'storage/canceled':
        // User canceled the download
        break;

      // ...

      case 'storage/unknown':
        // Unknown error occurred, inspect the server response
        break;
    }
  });

Web

// Create a reference to the file we want to download
var starsRef = storageRef.child('images/stars.jpg');

// Get the download URL
starsRef.getDownloadURL()
.then((url) => {
  // Insert url into an <img> tag to "download"
})
.catch((error) => {
  // A full list of error codes is available at
  // https://firebase.google.com/docs/storage/web/handle-errors
  switch (error.code) {
    case 'storage/object-not-found':
      // File doesn't exist
      break;
    case 'storage/unauthorized':
      // User doesn't have permission to access the object
      break;
    case 'storage/canceled':
      // User canceled the download
      break;

    // ...

    case 'storage/unknown':
      // Unknown error occurred, inspect the server response
      break;
  }
});

همچنین می‌توانید برای فایل‌هایی که در Cloud Storage ذخیره شده‌اند، فراداده دریافت یا به‌روز کنید.