【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;

Image.jsx

import React from 'react';

const Image = (props) => {
  return (
    <React.Fragment>
      <img src={props.url} alt={props.name} />
    </React.Fragment>
  );
}

export default Image;

Upload.jsx

import React, { useState } from 'react';
import { ref, uploadBytes } from 'firebase/storage';
import { storage } from '../scripts/firebase';
import Image from './Image';

const getDataURL = (file) => {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.onload = () => {
      const dataURL = reader.result;
      resolve(dataURL);
    }
    reader.readAsDataURL(file);
  });
}

const Upload = () => {
  const [files, setFiles] = useState([]);
  const [images, setImages] = useState([]);

  const handleInputChange = async (event) => {
    const fileList = Array.from(event.target.files);
    const imageList = [];
    for (const file of fileList) {
      const dataURL = await getDataURL(file);
      imageList.push(
        <Image key={file.name} url={dataURL} name={file.name} />
      );
    }
    setFiles(fileList);
    setImages(imageList);
  }

  const handleSubmit = (event) => {
    event.preventDefault();
    files.forEach((file) => {
      const storageRef = ref(storage, `images/${file.name}`);
      uploadBytes(storageRef, file).then(() => {
        console.log('Uploaded!');
      });
    });
  }

  return (
    <React.Fragment>
      <form>
        <input
          type='file'
          accept='image/*'
          multiple
          onChange={handleInputChange}
        />
        <button type='submit' onClick={handleSubmit}>送信</button>
      </form>
      { images }
    </React.Fragment>
  );
}

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