Tải tệp xuống bằng Cloud Storage trên web

Cloud Storage for Firebase cho phép bạn tải xuống nhanh chóng và dễ dàng tệp từ Cloud Storage bộ chứa do Firebase cung cấp và quản lý.

Tạo tệp đối chiếu

Để tải một tệp xuống, trước tiên tạo một tệp đối chiếu Cloud Storage vào tệp bạn muốn tải xuống.

Bạn có thể tạo một tệp tham chiếu bằng cách thêm đường dẫn con vào thư mục gốc của bộ chứa Cloud Storage hoặc tạo một tệp tham chiếu từ URL gs:// hoặc https:// hiện có tham chiếu đến một đối tượng trong Cloud Storage.

Web

import { getStorage, ref } from "firebase/storage";

// Create a reference with an initial file path and name
const storage = getStorage();
const pathReference = ref(storage, 'images/stars.jpg');

// Create a reference from a Google Cloud Storage URI
const gsReference = ref(storage, 'gs://bucket/images/stars.jpg');

// Create a reference from an HTTPS URL
// Note that in the URL, characters are URL escaped!
const httpsReference = ref(storage, 'https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg');  

Web

// Create a reference with an initial file path and name
var storage = firebase.storage();
var pathReference = storage.ref('images/stars.jpg');

// Create a reference from a Google Cloud Storage URI
var gsReference = storage.refFromURL('gs://bucket/images/stars.jpg');

// Create a reference from an HTTPS URL
// Note that in the URL, characters are URL escaped!
var httpsReference = storage.refFromURL('https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg');  

Tải dữ liệu xuống qua URL

Bạn có thể lấy URL tải xuống cho một tệp bằng cách gọi hàm Phương thức getDownloadURL() trên tham chiếu Cloud Storage.

Web

import { getStorage, ref, getDownloadURL } from "firebase/storage";

const storage = getStorage();
getDownloadURL(ref(storage, 'images/stars.jpg'))
  .then((url) => {
    // `url` is the download URL for 'images/stars.jpg'

    // This can be downloaded directly:
    const xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = (event) => {
      const blob = xhr.response;
    };
    xhr.open('GET', url);
    xhr.send();

    // Or inserted into an <img> element
    const img = document.getElementById('myimg');
    img.setAttribute('src', url);
  })
  .catch((error) => {
    // Handle any errors
  });

Web

storageRef.child('images/stars.jpg').getDownloadURL()
  .then((url) => {
    // `url` is the download URL for 'images/stars.jpg'

    // This can be downloaded directly:
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = (event) => {
      var blob = xhr.response;
    };
    xhr.open('GET', url);
    xhr.send();

    // Or inserted into an <img> element
    var img = document.getElementById('myimg');
    img.setAttribute('src', url);
  })
  .catch((error) => {
    // Handle any errors
  });

Tải dữ liệu xuống trực tiếp từ SDK

Từ phiên bản 9.5 trở lên, SDK cung cấp các hàm sau để tải xuống trực tiếp:

Khi sử dụng các hàm này, bạn có thể bỏ qua việc tải xuống từ URL và thay vào đó, trả về dữ liệu trong mã. Điều này cho phép kiểm soát quyền truy cập chi tiết hơn thông qua Firebase Security Rules.

Cấu hình CORS

Để tải dữ liệu xuống trực tiếp trong trình duyệt, bạn phải định cấu hình Bộ chứa Cloud Storage để truy cập nhiều nguồn gốc (CORS). Có thể làm được bằng công cụ dòng lệnh gsutil. Bạn có thể cài đặt từ đây.

Nếu bạn không muốn có bất kỳ quy định hạn chế nào dựa trên miền (trường hợp phổ biến nhất), hãy sao chép tệp JSON này vào một tệp có tên cors.json:

[
  {
    "origin": ["*"],
    "method": ["GET"],
    "maxAgeSeconds": 3600
  }
]

Chạy gsutil cors set cors.json gs://<your-cloud-storage-bucket> để triển khai các quy định hạn chế này.

Để biết thêm thông tin, hãy tham khảo tài liệu về Google Cloud Storage.

Xử lý lỗi

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

Ví dụ đầy đủ

Dưới đây là ví dụ đầy đủ về một tệp tải xuống có cách xử lý lỗi:

Web

import { getStorage, ref, getDownloadURL } from "firebase/storage";

// Create a reference to the file we want to download
const storage = getStorage();
const starsRef = ref(storage, 'images/stars.jpg');

// Get the download URL
getDownloadURL(starsRef)
  .then((url) => {
    // Insert url into an <img> tag to "download"
  })
  .catch((error) => {
    // A full list of error codes is available at
    // https://firebase.google.com/docs/storage/web/handle-errors
    switch (error.code) {
      case 'storage/object-not-found':
        // File doesn't exist
        break;
      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 the server response
        break;
    }
  });

Web

// Create a reference to the file we want to download
var starsRef = storageRef.child('images/stars.jpg');

// Get the download URL
starsRef.getDownloadURL()
.then((url) => {
  // Insert url into an <img> tag to "download"
})
.catch((error) => {
  // A full list of error codes is available at
  // https://firebase.google.com/docs/storage/web/handle-errors
  switch (error.code) {
    case 'storage/object-not-found':
      // File doesn't exist
      break;
    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 the server response
      break;
  }
});

Bạn cũng có thể tải hoặc cập nhật siêu dữ liệu cho các tệp được lưu trữ trong Cloud Storage.