Skip to content

Instantly share code, notes, and snippets.

@DZuz14
Last active July 13, 2021 15:42
Show Gist options
  • Save DZuz14/51e73607164a885163cdb87c51e4ec9d to your computer and use it in GitHub Desktop.
Save DZuz14/51e73607164a885163cdb87c51e4ec9d to your computer and use it in GitHub Desktop.
Upload Last
const Upload = () => {
const [files, setFiles] = useState([])
const inputRef = useRef()
const handleClick = () => {
inputRef.current.click()
}
const handleFiles = (fileList, mode = 'w') => {
if (mode === 'a') {
setFiles((prevFiles) => [...prevFiles, ...Array.from(fileList)])
} else if (mode === 'w') {
setFiles(Array.from(fileList))
}
}
const removeFile = (name) => {
const newFiles = files.filter((file) => file.name !== name)
setFiles(newFiles)
}
const preventBubbling = (e) => {
e.stopPropagation()
e.preventDefault()
}
const handleSubmit = async () => {
const formData = new FormData()
for (const file of files) {
formData.append(file.name, file)
}
try {
axios.post('https://some-api.com/<route here>', formData, {
'Content-Type': 'multipart/form-data'
})
} catch (error) {
console.error('Failed to submit files.')
}
}
return (
<div className="Upload" css={CSS}>
<div className="inner">
<div className="list">
<h5>Your Files:</h5>
{files && (
<ul className="files">
{files.map((file, i) => (
<li key={file.name} onClick={() => removeFile(file.name)}>
{i + 1}. {file.name}
<span>
<i className="fa fa-times" />
</span>
</li>
))}
</ul>
)}
</div>
<div
className="form"
onDragEnter={preventBubbling}
onDragOver={preventBubbling}
onDrop={(e) => {
preventBubbling(e)
handleFiles(e.dataTransfer.files, 'a')
}}
>
<i className="fa fa-cloud-upload fa-4x"></i>
<p>Drag and drop files or select files below.</p>
<input
ref={inputRef}
type="file"
multiple
style={{ display: 'none' }}
onChange={(e) => handleFiles(e.target.files, 'a')}
/>
<button onClick={handleClick}>Choose Files</button>
</div>
</div>
<button id="submit" onClick={handleSubmit}>
Submit
</button>
</div>
)
}
const CSS = css`
...other css
#submit {
position: absolute;
bottom: 120px;
left: calc(50% - 66px);
}
`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment