ウェブで Cloud Storage を使用してファイルをダウンロードする

Cloud Storage for Firebase を使用すると、Firebase によって提供、管理される Cloud Storage バケットからファイルを迅速かつ容易にダウンロードできます。

参照を作成する

ファイルをダウンロードするには、まずダウンロードするファイルへの Cloud Storage 参照を作成します。

参照は、Cloud Storage バケットのルートに子パスを付加して作成することも、Cloud Storage のオブジェクトを参照する既存の gs:// または https:// URL から作成することもできます。

ウェブ向けのモジュラー API

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

ウェブ向けの名前空間付き API

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

URL 経由でデータをダウンロードする

ファイルのダウンロード URL を取得するには、Cloud Storage 参照で getDownloadURL() メソッドを呼び出します。

ウェブ向けのモジュラー API

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

ウェブ向けの名前空間付き API

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

SDK からデータを直接ダウンロードする

SDK version 9.5 以降では、直接ダウンロードできる次の関数が SDK によって提供されています。

これらの関数を使用すると、URL からのダウンロードを回避し、コード内にデータを返せます。これにより、Firebase セキュリティ ルールを使用して、きめ細かいアクセス制御を行うことができます。

CORS の構成

ブラウザで直接データをダウンロードするには、Cloud Storage バケットに対してクロスオリジン アクセス(CORS)を構成する必要があります。この構成は gsutil コマンドライン ツールを使って行います。ツールはここからインストールしてください。

ドメインベースの制限が必要ない場合(最もよくある状況)、次の JSON を cors.json という名前のファイルにコピーします。

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

これらの制限をデプロイするには、gsutil cors set cors.json gs://<your-cloud-storage-bucket> を実行します。

詳細については、Google Cloud Storage のドキュメントをご覧ください。

エラーの処理

ダウンロード時にエラーが発生する理由としては、ファイルが存在しない、目的のファイルへのアクセス権がないなど、多くの理由が考えられます。エラーの詳細については、このドキュメントのエラーを処理するのセクションをご覧ください。

ダウンロードとエラー処理の完全な例を以下に示します。

ウェブ向けのモジュラー API

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

ウェブ向けの名前空間付き API

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

Cloud Storage に保存されているファイルのメタデータを取得、更新することもできます。