Last active
December 1, 2020 03:15
-
-
Save Fabianopb/4595924936c8c92c83e3dd75bc58ec9e to your computer and use it in GitHub Desktop.
React component for single file upload.
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 axios from 'axios'; | |
const FileUpload = () => { | |
// If you are using TypeScript the state will be | |
// const [file, setFile] = useState<FileList | null>(null); | |
const [file, setFile] = useState(null); | |
const submitFile = async () => { | |
try { | |
if (!file) { | |
throw new Error('Select a file first!'); | |
} | |
const formData = new FormData(); | |
formData.append('file', file[0]); | |
await axios.post(`/test-upload`, formData, { | |
headers: { | |
'Content-Type': 'multipart/form-data', | |
}, | |
}); | |
// handle success | |
} catch (error) { | |
// handle error | |
} | |
}; | |
return ( | |
<form onSubmit={submitFile}> | |
<label>Upload file</label> | |
<input type="file" onChange={event => setFile(event.target.files)} /> | |
<button type="submit">Send</button> | |
</form> | |
); | |
}; | |
export default FileUpload; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment