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 file = event.target.files[0];
const storageRef = ref(storage, `images/${file.name}`);
uploadBytes(storageRef, file).then(() => {
console.log('Uploaded!');
});
}
return (
<React.Fragment>
<input type='file' onChange={handleInputChange} />
</React.Fragment>
);
}
export default Upload;
参考
ウェブで Cloud Storage を使用してファイルをアップロードする | Cloud Storage for Firebase