อัปโหลดไฟล์ด้วย 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 

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 API และ File และ Blob แล้วอัปโหลดไปยัง 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!');
});

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

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() เพื่ออัปโหลดสตริงที่เข้ารหัสแบบ RAW, 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!');
});

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

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

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 เช่น

ประเภทเหตุการณ์ การใช้งานทั่วไป
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);
    });
  }
);

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

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 กัน