Created
January 30, 2021 15:23
-
-
Save agmm/5ceeff55a5e658365b5ce258c235cbdd to your computer and use it in GitHub Desktop.
Upload file to a firebase storage bucket — React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from "react"; | |
import firebase from "firebase"; | |
import "firebase/storage"; | |
const firebaseConfig = {}; | |
if (!firebase.apps.length) { | |
firebase.initializeApp(firebaseConfig); | |
} | |
export const storage = firebase.storage(); | |
function UploadForm() { | |
const [file, setFile] = useState(null); | |
const [url, setURL] = useState(""); | |
function handleChange(e) { | |
setFile(e.target.files[0]); | |
} | |
function handleUpload(e) { | |
e.preventDefault(); | |
const uploadTask = storage.ref(`/images/${file.name}`).put(file); | |
uploadTask.on("state_changed", console.log, console.error, () => { | |
storage | |
.ref("images") | |
.child(file.name) | |
.getDownloadURL() | |
.then((url) => { | |
setFile(null); | |
setURL(url); | |
}); | |
}); | |
} | |
return ( | |
<div> | |
<form onSubmit={handleUpload}> | |
<input type='file' onChange={handleChange} /> | |
<button disabled={!file}>Upload to firebase</button> | |
</form> | |
<img src={url} alt='' /> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment