Cloud Storage for Firebase を使用すると、Firebase が提供および管理するCloud Storageバケットからファイルをすばやく簡単にダウンロードできます。
参照を作成する
ファイルをダウンロードするには、まずダウンロードするファイルへの Cloud Storage 参照を作成します。
Cloud Storage バケットのルートに子パスを追加して参照を作成するか、Cloud Storage 内のオブジェクトを参照する既存のgs://
またはhttps://
URL から参照を作成できます。
Web version 9
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 version 8
// 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()
メソッドを呼び出します。
Web version 9
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 version 8
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 から直接データをダウンロードする
バージョン 9.5 以降では、SDK は直接ダウンロード用に次の機能を提供します。
これらの関数を使用すると、URL からのダウンロードをバイパスし、代わりにコードでデータを返すことができます。これにより、 Firebase Security Rulesを介してよりきめ細かいアクセス制御が可能になります。
CORS 構成
ブラウザでデータを直接ダウンロードするには、クロスオリジン アクセス(CORS)用に Cloud Storage バケットを構成する必要があります。これは、ここからインストールできるgsutil
コマンドライン ツールで実行できます。
ドメインベースの制限が不要な場合 (最も一般的なシナリオ)、この JSON をcors.json
という名前のファイルにコピーします:
[ { "origin": ["*"], "method": ["GET"], "maxAgeSeconds": 3600 } ]
gsutil cors set cors.json gs://<your-cloud-storage-bucket>
を実行して、これらの制限をデプロイします。
詳細については、 Google Cloud Storage のドキュメントを参照してください。
エラー処理
ファイルが存在しない、またはユーザーが目的のファイルにアクセスする権限を持っていないなど、ダウンロード時にエラーが発生する理由はいくつかあります。エラーの詳細については、ドキュメントの「エラーの処理」セクションを参照してください。
完全な例
エラー処理を含むダウンロードの完全な例を以下に示します。
Web version 9
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 version 8
// 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 に保存されているファイルのメタデータを取得または更新することもできます。