【Firebase】複数のファイルをアップロードできるようにする

firebase.js

import { initializeApp } from "firebase/app";
import { getStorage } from "firebase/storage";

const firebaseConfig = {
  apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
  authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.REACT_APP_FIREBASE_APP_ID,
  measurementId: process.env.REACT_APP_FIREBASE_MEASUREMENT_ID
};

const app = initializeApp(firebaseConfig);
export const storage = getStorage(app);

App.jsx

import React from 'react';
import Upload from './Upload';

const App = () => {
  return (
    <React.Fragment>
      <Upload />
    </React.Fragment>
  );
}

export default App;

Upload.jsx

import React from 'react';
import { ref, uploadBytes } from 'firebase/storage';
import { storage } from '../scripts/firebase';
  
const Upload = () => {
  const handleInputChange = (event) => {
    const files = Array.from(event.target.files);
    files.forEach((file) => {
      const storageRef = ref(storage, `images/${file.name}`);
      uploadBytes(storageRef, file).then(() => {
        console.log('Uploaded!');
      });
    });
  }

  return (
    <React.Fragment>
      <input
        type='file'
        accept='image/*'
        multiple
        onChange={handleInputChange}
      />
    </React.Fragment>
  );
}

export default Upload;
タイトルとURLをコピーしました