העלה קבצים עם 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 

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() לוקח קבצים דרך ממשקי JavaScript File ו- Blob API ומעלה אותם ל-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!');
});

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

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

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 . מידע נוסף על מטא נתונים של קבצים ניתן למצוא בסעיף השתמש במטא נתונים של קבצים .

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() , 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 observer, כגון:

סוג אירוע שימוש אופייני
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);
    });
  }
);

טיפול בשגיאות

ישנן מספר סיבות לכך שגיאות עלולות להתרחש בהעלאה, כולל הקובץ המקומי אינו קיים, או שלמשתמש אין הרשאה להעלות את הקובץ הרצוי. מידע נוסף על שגיאות ניתן למצוא בקטע טיפול בשגיאות במסמכים.

דוגמה מלאה

דוגמה מלאה להעלאה עם ניטור התקדמות וטיפול בשגיאות מוצגת להלן:

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

כעת, לאחר שהעלית קבצים, בואו ללמוד כיצד להוריד אותם מ-Cloud Storage.