Skip to content

Instantly share code, notes, and snippets.

@jonahgeek
Created October 14, 2021 07:53
Show Gist options
  • Save jonahgeek/9c7bf141132fd165810a0e0ed3ccba79 to your computer and use it in GitHub Desktop.
Save jonahgeek/9c7bf141132fd165810a0e0ed3ccba79 to your computer and use it in GitHub Desktop.
Handling image upload in react
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