העלאת קבצים באמצעות Cloud Storage באינטרנט

בדף הזה מוסבר איך להשתמש ב-SDK של Cloud Storage for Firebase כדי להעלות קבצים לקטגוריה של Cloud Storage.

מידע נוסף זמין בשאלות הנפוצות האלה.

העלאת קבצים

כדי להעלות קובץ אל Cloud Storage, קודם צריך ליצור הפניה לנתיב המלא של הקובץ, כולל שם הקובץ.

Web

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

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

אחרי שיוצרים קובץ עזר מתאים, אפשר להפעיל את ה-method‏ uploadBytes(). ‫uploadBytes() מקבל קבצים דרך ממשקי ה-API של JavaScript,‏ File ו-Blob, ואז מעלה אותם אל Cloud Storage.

Web

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

// 'file' comes from the Blob or File API
ref.put(file).then((snapshot) => {
  console.log('Uploaded a blob or file!');
});

העלאה ממערך בייטים

בנוסף לסוגי הקבצים File ו-Blob, אפשר להעלות ל-Cloud Storage גם קובץ Uint8Array באמצעות uploadBytes().

Web

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

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

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

// 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 מסיק באופן אוטומטי את סוג ה-MIME מסיומת הקובץ שבו הקובץ מאוחסן בדיסק, אבל אם מציינים contentType במטא-נתונים, הוא יחליף את הסוג שזוהה באופן אוטומטי. אם לא צוינו מטא-נתונים של contentType ולקובץ אין סיומת קובץ, Cloud Storage יוגדר כברירת מחדל לסוג application/octet-stream. מידע נוסף על מטא-נתונים של קבצים זמין במאמר שימוש במטא-נתונים של קבצים.

Web

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

// 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. קריאה ל-method‏ cancel() תגרום להעלאה להיכשל ותחזיר שגיאה שמציינת שההעלאה בוטלה.

Web

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

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

מעקב אחרי התקדמות ההעלאה

בזמן ההעלאה, משימת ההעלאה עשויה להעלות אירועי התקדמות ב-observer של 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

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

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

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

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