تنزيل الملفات باستخدام Cloud Storage على الويب

تتيح لك خدمة Cloud Storage for Firebase تنزيل الملفات بسرعة وسهولة من حزمة Cloud Storage التي توفّرها منصة Firebase وتديرها.

إنشاء مرجع

لتنزيل ملف، عليك أولاً إنشاء مرجع Cloud Storage للملف الذي تريد تنزيله.

يمكنك إنشاء مرجع من خلال إلحاق مسارات فرعية بجذر حزمة Cloud Storage، أو يمكنك إنشاء مرجع من عنوان URL حالي للسمة gs:// أو https:// يشير إلى عنصر في Cloud Storage.

واجهة برمجة التطبيقات Web modular API

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

واجهة برمجة التطبيقات لمساحة الاسم على الويب

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

تنزيل البيانات عبر عنوان URL

يمكنك الحصول على عنوان URL لتنزيل ملف من خلال استدعاء طريقة getDownloadURL() في مرجع Cloud Storage.

واجهة برمجة التطبيقات Web modular API

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

const storage = getStorage();
getDownloadURL(ref(storage, 'images/stars.jpg'))
  .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
  });

واجهة برمجة التطبيقات لمساحة الاسم على الويب

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

تنزيل البيانات مباشرةً من حزمة SDK

توفّر حزمة تطوير البرامج (SDK) الوظائف التالية للتنزيل المباشر، وذلك بدايةً من الإصدار 9.5 والإصدارات الأحدث:

باستخدام هذه الدوال، يمكنك تجاوز التنزيل من عنوان URL، وبدلاً من ذلك عرض البيانات في التعليمات البرمجية الخاصة بك. يتيح ذلك التحكُّم في الوصول إلى البيانات بشكل أكثر دقة من خلال قواعد أمان Firebase.

إعداد CORS

لتنزيل البيانات مباشرةً في المتصفّح، عليك ضبط حزمة Cloud Storage للوصول من مصادر متعددة (CORS). ويمكن إجراء ذلك باستخدام أداة سطر الأوامر gsutil التي يمكنك تثبيتها من هنا.

إذا لم تكن تريد أيّ قيود مستندة إلى النطاق (السيناريو الأكثر شيوعًا)، انسخ ملف JSON هذا إلى ملف باسم cors.json:

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

يمكنك تشغيل gsutil cors set cors.json gs://<your-cloud-storage-bucket> لنشر هذه القيود.

لمزيد من المعلومات، راجِع مستندات Google Cloud Storage.

التعامل مع الأخطاء

هناك عدة أسباب قد تؤدي إلى حدوث أخطاء عند التنزيل، منها عدم توفّر الملف أو عدم حصول المستخدم على إذن بالوصول إلى الملف المطلوب. يمكن العثور على مزيد من المعلومات حول الأخطاء في قسم معالجة الأخطاء في المستندات.

مثال كامل

في ما يلي مثال كامل لعملية تنزيل تم التعامل مع أخطاء فيها:

واجهة برمجة التطبيقات Web modular API

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 upload
        break;

      // ...

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

واجهة برمجة التطبيقات لمساحة الاسم على الويب

// 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 upload
      break;

    // ...

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

يمكنك أيضًا الحصول على البيانات الوصفية أو تعديلها للملفات المخزَّنة في Cloud Storage.