"Upload Image IN React Js with FormData"
Bootstrap 4.1.1 Snippet by Arjunverma

<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <!------ Include the above in your HEAD tag ----------> <div> <h2>Upload Image</h2> <p>Using FormData</p> </div>
import React from 'react'; import { fireToast } from '../helper'; import axiosInstance from '../auth/axiosInstance'; import { Formik } from 'formik'; import axios from 'axios'; const Orders = () => { return ( <div> <h2>Orders</h2> <p>Manage your orders here.</p> <Formik initialValues={{ profile: [] }} validate={values => { const errors = {}; if (values.profile.length === 0) { errors.profile = 'Required'; } return errors; }} onSubmit={(values, { setSubmitting }) => { setSubmitting(true); const formData = new FormData(); values.profile.forEach((file, index) => { formData.append('profile', file); // Adding '[]' for an array of files }); axiosInstance.post(process.env.REACT_APP_BASE_URL + `api/users/uploadProfile`, formData) .then((res) => { if (res.status === 200) { fireToast('success', res?.data?.message); } }) .catch((error) => { console.log(error) fireToast('error', error?.response?.data?.error); }) .finally(() => { setSubmitting(false); }); }} > {({ values, errors, touched, handleChange, handleBlur, handleSubmit, setFieldValue, isSubmitting, }) => ( <form onSubmit={handleSubmit}> <div className='row'> <div className='col-lg-6'> <div> <p>Image</p> <input type="file" name="profile" accept="image/*" multiple onChange={(event) => { const files = Array.from(event.target.files); setFieldValue("profile", files); }} onBlur={handleBlur} /> {errors.profile && touched.profile && <div>{errors.profile}</div>} </div> </div> </div> <button type="submit" disabled={isSubmitting}> Submit </button> </form> )} </Formik> </div> ); }; export default Orders;

Related: See More


Questions / Comments: