1 changed files with 62 additions and 0 deletions
@ -0,0 +1,62 @@ |
|||||||
|
import React, { useState } from "react"; |
||||||
|
import { storage, firestore } from "firebase/app"; |
||||||
|
import "firebase/storage"; |
||||||
|
import "firebase/firestore"; |
||||||
|
|
||||||
|
function ImageUpload() { |
||||||
|
const [image, setImage] = useState(null); |
||||||
|
const [imageUrl, setImageUrl] = useState(""); |
||||||
|
const [progress, setProgress] = useState(0); |
||||||
|
|
||||||
|
const handleChange = (e) => { |
||||||
|
if (e.target.files[0]) { |
||||||
|
setImage(e.target.files[0]); |
||||||
|
} |
||||||
|
}; |
||||||
|
|
||||||
|
const handleUpload = () => { |
||||||
|
const uploadTask = storage.ref(`images/${image.name}`).put(image); |
||||||
|
|
||||||
|
uploadTask.on( |
||||||
|
"state_changed", |
||||||
|
(snapshot) => { |
||||||
|
const progress = Math.round( |
||||||
|
(snapshot.bytesTransferred / snapshot.totalBytes) * 100 |
||||||
|
); |
||||||
|
setProgress(progress); |
||||||
|
}, |
||||||
|
(error) => { |
||||||
|
console.log(error); |
||||||
|
}, |
||||||
|
() => { |
||||||
|
storage |
||||||
|
.ref("images") |
||||||
|
.child(image.name) |
||||||
|
.getDownloadURL() |
||||||
|
.then((url) => { |
||||||
|
setImageUrl(url); |
||||||
|
firestore() |
||||||
|
.collection("images") |
||||||
|
.add({ |
||||||
|
imageUrl, |
||||||
|
createdAt: new Date(), |
||||||
|
}) |
||||||
|
.then(() => { |
||||||
|
setProgress(0); |
||||||
|
setImage(null); |
||||||
|
}); |
||||||
|
}); |
||||||
|
} |
||||||
|
); |
||||||
|
}; |
||||||
|
|
||||||
|
return ( |
||||||
|
<div> |
||||||
|
<input type="file" onChange={handleChange} /> |
||||||
|
<button onClick={handleUpload}>Upload</button> |
||||||
|
<progress value={progress} max="100" /> |
||||||
|
</div> |
||||||
|
); |
||||||
|
} |
||||||
|
|
||||||
|
export default ImageUpload; |
||||||
Loading…
Reference in new issue