FirebaseファイルストレージをReactアプリに統合する

Firebase Storageを利用すると、画像や動画、ドキュメントなどのファイルを効率的に保存および取得できます。ReactアプリケーションでFirebaseファイルストレージを統合し、ファイルアップロードとダウンロードを実現する方法を具体的に説明します。
目次
Firebaseプロジェクトの作成
Firebaseコンソールで新しいプロジェクトを作成し、Storageを有効にします。
Firebase SDKのインストール
必要なFirebaseモジュールをインストールします。
npm install firebase
Firebaseの初期設定
Firebase設定ファイルを作成し、プロジェクトの設定情報を追加します。
import { initializeApp } from "firebase/app";
import { getStorage } from "firebase/storage";
const firebaseConfig = {
apiKey: "your_api_key",
authDomain: "your_project_id.firebaseapp.com",
projectId: "your_project_id",
storageBucket: "your_project_id.appspot.com",
messagingSenderId: "your_messaging_sender_id",
appId: "your_app_id"
};
const app = initializeApp(firebaseConfig);
export const storage = getStorage(app);
ファイルアップロードコンポーネントの作成
Reactでファイルアップロードフォームを構築します。
import React, { useState } from "react";
import { storage } from "./firebase";
import { ref, uploadBytes, getDownloadURL } from "firebase/storage";
function FileUpload() {
const [file, setFile] = useState(null);
const handleFileChange = (e) => {
setFile(e.target.files[0]);
};
const handleUpload = async () => {
if (!file) return;
const storageRef = ref(storage, `uploads/${file.name}`);
try {
await uploadBytes(storageRef, file);
const url = await getDownloadURL(storageRef);
console.log("File uploaded successfully. URL:", url);
} catch (error) {
console.error("Upload failed:", error);
}
};
return (
<div>
<input type="file" onChange={handleFileChange} />
<button onClick={handleUpload}>Upload</button>
</div>
);
}
アップロードされたファイルの取得
保存されたファイルのURLを取得して表示します。
ファイルリストの表示
アップロードされた複数のファイルを一覧表示する機能を追加します。
import { listAll, ref } from "firebase/storage";
async function fetchFiles() {
const listRef = ref(storage, "uploads/");
try {
const res = await listAll(listRef);
res.items.forEach(async (itemRef) => {
const url = await getDownloadURL(itemRef);
console.log("File URL:", url);
});
} catch (error) {
console.error("Failed to fetch files:", error);
}
}
ファイル削除機能の追加
不要なファイルを削除する機能を実装します。
import { deleteObject } from "firebase/storage";
async function deleteFile(filePath) {
const fileRef = ref(storage, filePath);
try {
await deleteObject(fileRef);
console.log("File deleted successfully");
} catch (error) {
console.error("File deletion failed:", error);
}
}
進捗表示の実装
アップロード中の進捗状況を表示します。
import { uploadBytesResumable } from "firebase/storage";
const handleUploadWithProgress = (file) => {
const storageRef = ref(storage, `uploads/${file.name}`);
const uploadTask = uploadBytesResumable(storageRef, file);
uploadTask.on(
"state_changed",
(snapshot) => {
const progress =
(snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log("Upload is " + progress + "% done");
},
(error) => {
console.error("Upload failed:", error);
},
() => {
console.log("Upload complete");
}
);
};
React Contextでストレージ機能を共有
Contextを使用してアプリ全体でストレージインスタンスを共有します。
フォルダ構造の設計
ファイルの分類や整理に役立つフォルダ構造を考慮します。
セキュリティルールの設定
Firebase Storageでのアクセス制御を設定します。
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /uploads/{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
ファイルサイズの制限
アップロード可能なファイルサイズを制限します。
UI/UXの改善
ドラッグ&ドロップやプレビュー機能を追加してユーザー体験を向上させます。
まとめ
Firebase StorageはReactアプリにおいて簡単かつ柔軟なファイル管理を可能にします。適切な設計と実装で効率的なアプリケーションを構築しましょう。
-
前の記事
MySQLのエラー『エラー1142: Command Denied』の解決方法 2025.04.22
-
次の記事
Syntax Error: Unexpected token in Vue component templateの解決方法 2025.04.22
コメントを書く