อัปโหลดไฟล์ด้วย Cloud Storage บนเว็บ

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

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 ผู้สังเกตการณ์ เช่น:

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