Tải tệp lên bằng Cloud Storage trên Web

Cloud Storage cho Firebase cho phép bạn tải tệp lên nhóm Cloud Storage do Firebase cung cấp và quản lý một cách nhanh chóng và dễ dàng.

Tải tập tin lên

Để tải tệp lên Cloud Storage, trước tiên bạn tạo tham chiếu đến đường dẫn đầy đủ của tệp, bao gồm cả tên tệp.

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 

Tải lên từ Blob hoặc File

Khi bạn đã tạo một tham chiếu thích hợp, bạn gọi phương thức uploadBytes() . uploadBytes() lấy tệp thông qua API tệp JavaScript và Blob rồi tải chúng lên 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!');
});

Tải lên từ một mảng Byte

Ngoài các loại FileBlob , uploadBytes() cũng có thể tải Uint8Array lên 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!');
});

Tải lên từ một chuỗi

Nếu không có Blob , File hoặc Uint8Array thì bạn có thể sử dụng phương thức uploadString() để tải chuỗi mã hóa thô, base64 , base64url hoặc data_url lên 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!');
});

Vì tham chiếu xác định đường dẫn đầy đủ đến tệp nên hãy đảm bảo rằng bạn đang tải lên đường dẫn không trống.

Thêm siêu dữ liệu tệp

Khi tải tệp lên, bạn cũng có thể chỉ định siêu dữ liệu cho tệp đó. Siêu dữ liệu này chứa các thuộc tính siêu dữ liệu tệp điển hình như name , sizecontentType (thường được gọi là loại MIME). Cloud Storage tự động phỏng đoán loại nội dung từ phần mở rộng tệp nơi tệp được lưu trữ trên đĩa nhưng nếu bạn chỉ định một contentType trong siêu dữ liệu thì nó sẽ ghi đè loại được tự động phát hiện. Nếu không có siêu dữ liệu contentType nào được chỉ định và tệp không có phần mở rộng tệp thì Cloud Storage sẽ mặc định là loại application/octet-stream . Bạn có thể tìm thêm thông tin về siêu dữ liệu tệp trong phần Sử dụng siêu dữ liệu tệp .

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

Quản lý tải lên

Ngoài việc bắt đầu tải lên, bạn có thể tạm dừng, tiếp tục và hủy tải lên bằng các phương thức pause() , resume()cancel() . Việc gọi pause() hoặc resume() sẽ làm tăng các thay đổi trạng thái pause hoặc running . Việc gọi phương thức cancel() sẽ dẫn đến việc tải lên không thành công và trả về lỗi cho biết quá trình tải lên đã bị hủy.

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

Theo dõi tiến trình tải lên

Trong khi tải lên, tác vụ tải lên có thể đưa ra các sự kiện tiến trình trong trình quan sát state_changed , chẳng hạn như:

Loại sự kiện Cách sử dụng điển hình
running Sự kiện này kích hoạt khi tác vụ bắt đầu hoặc tiếp tục tải lên và thường được sử dụng cùng với sự kiện pause . Đối với các video tải lên lớn hơn, sự kiện này có thể kích hoạt nhiều lần dưới dạng cập nhật tiến trình.
pause Sự kiện này kích hoạt bất cứ khi nào quá trình tải lên bị tạm dừng và thường được sử dụng cùng với sự kiện running .

Khi một sự kiện xảy ra, một đối tượng TaskSnapshot sẽ được truyền trở lại. Ảnh chụp nhanh này là chế độ xem bất biến của nhiệm vụ tại thời điểm sự kiện xảy ra. Đối tượng này chứa các thuộc tính sau:

Tài sản Kiểu Sự miêu tả
bytesTransferred Number Tổng số byte đã được chuyển khi chụp ảnh nhanh này.
totalBytes Number Tổng số byte dự kiến ​​sẽ được tải lên.
state firebase.storage.TaskState Trạng thái tải lên hiện tại.
metadata firebaseStorage.Metadata Trước khi quá trình tải lên hoàn tất, siêu dữ liệu sẽ được gửi đến máy chủ. Sau khi quá trình tải lên hoàn tất, siêu dữ liệu mà máy chủ sẽ gửi lại.
task firebaseStorage.UploadTask Tác vụ này là một ảnh chụp nhanh, có thể được sử dụng để `tạm dừng`, `tiếp tục` hoặc `hủy` tác vụ.
ref firebaseStorage.Reference Các tài liệu tham khảo nhiệm vụ này đến từ.

Những thay đổi về trạng thái này, kết hợp với các thuộc tính của TaskSnapshot , cung cấp một cách đơn giản nhưng mạnh mẽ để giám sát các sự kiện tải lên.

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

Xử lý lỗi

Có một số lý do khiến lỗi có thể xảy ra khi tải lên, bao gồm cả tệp cục bộ không tồn tại hoặc người dùng không có quyền tải tệp mong muốn lên. Bạn có thể tìm thêm thông tin về lỗi trong phần Xử lý lỗi của tài liệu.

Ví dụ đầy đủ

Dưới đây là ví dụ đầy đủ về quá trình tải lên có theo dõi tiến trình và xử lý lỗi:

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

Bây giờ bạn đã tải tệp lên, hãy tìm hiểu cách tải chúng xuống từ Cloud Storage.