Skip to content

Instantly share code, notes, and snippets.

@jgcmarins
Last active January 9, 2020 18:50
Show Gist options
  • Select an option

  • Save jgcmarins/6eb214761b3c2878b8d0a263e9b10e4d to your computer and use it in GitHub Desktop.

Select an option

Save jgcmarins/6eb214761b3c2878b8d0a263e9b10e4d to your computer and use it in GitHub Desktop.
import React, { useCallback, useState } from "react"
import { useDropzone } from "react-dropzone"
import mime from "mime-types"
import firebase, { storage } from "../../firebase/firebaseServices"
interface IFileUpload {
path: string,
onUpload: (filePath: string) => void,
}
function FileUpload({ path, onUpload }: IFileUpload) {
const storageRef = storage.ref()
const [isUploading, setIsUploading] = useState(false)
const [hasUploaded, setHasUploaded] = useState(false)
const [uploadMessage, setUploadMessage] = useState("")
const [uploadingProgress, setUploadingProgress] = useState(0)
// https://firebase.google.com/docs/storage/web/upload-files#full_example
const onDrop = useCallback(async (acceptedFiles) => {
setIsUploading(true)
const [file] = acceptedFiles
if (!file) return
const fileName = new Date().getTime() + "." + mime.extension(file.type).toString()
const options = {
lastModified: file.lastModified,
lastModifiedDate: file.lastModifiedDate,
type: file.type,
}
const fileToUpload = new File([file], fileName, options)
const metadata = {
contentType: file.type
}
const filePath = `${path}/${fileName}`
const uploadTask = storageRef.child(filePath).put(fileToUpload, metadata)
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
(snapshot) => {
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
setUploadingProgress(progress)
},
(error) => {
setIsUploading(false)
setHasUploaded(true)
setUploadMessage("Error uploading file")
console.log("Upload error", error)
},
async () => {
const downloadURL = await uploadTask.snapshot.ref.getDownloadURL()
setIsUploading(false)
setHasUploaded(true)
setUploadMessage("Upload completed")
onUpload(downloadURL)
}
)
}, [])
const { getRootProps, getInputProps } = useDropzone({onDrop})
return (
<>
<div {...getRootProps()}>
<input {...getInputProps()} type="file" />
</div>
</>
)
}
export default FileUpload;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment