Created
October 14, 2021 07:53
-
-
Save jonahgeek/9c7bf141132fd165810a0e0ed3ccba79 to your computer and use it in GitHub Desktop.
Handling image upload in 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
const handleImageUpload = async (e) => { | |
// get the file name | |
const file = e.target.files[0]; | |
// attach file | |
const bodyFormData = new FormData(); | |
bodyFormData.append("image", file); | |
// set fieldValue state | |
setFieldValue("image", bodyFormData); | |
try { | |
const { data } = await Axios.post( | |
`${YOUR_API_URL}/uploads`, bodyFormData, | |
{ | |
headers: { | |
"Content-Type": "multipart/form-data", | |
Authorization: `Bearer ${userInfo.token}`, | |
}, | |
} | |
); | |
setFieldValue("image", data); | |
} catch (error) { | |
setErrorUpload(error.message); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment