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

تتيح لك خدمة 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 

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

// 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 في JavaScript ويحمّلها إلى Cloud Storage.

واجهة برمجة التطبيقات 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!');
});

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

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

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

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

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

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

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

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

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

// 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 مرة أخرى. هذه اللقطة هي عرض غير قابل للتغيير للمهمة وقت وقوع الحدث. يحتوي هذا الكائن على السمات التالية:

الموقع Type الوصف
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);
    });
  }
);

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

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

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

// 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.