"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, { useState } from 'react' import { useSelector } from 'react-redux' import axios from 'axios' const Private = () => { const user = useSelector((state) => state.userReducer.user); const [formData, setFormData] = useState({ name: '', email: '', number: '', image: null // Start with null for file data }) const [pre, setPre] = useState('') const handleChange = (e) => { const { name, value } = e.target; setFormData({ ...formData, [name]: value }) } const handleFile = (e) => { let selectedFile = e.target.files[0]; // Correct way to access file console.log(selectedFile, "<<<<<"); setFormData({ ...formData, image: selectedFile }); if (selectedFile) { let previewUrl = URL.createObjectURL(selectedFile); // Corrected method to create preview setPre(previewUrl); } } const handleSubmit = (e) => { e.preventDefault(); const data = new FormData(); // Append all the fields to FormData data.append('name', formData.name); data.append('email', formData.email); data.append('number', formData.number); // If there is an image, append it to FormData if (formData.image) { data.append('image', formData.image); } // Send the data using axios axios.post('http://localhost:5900/save', data) .then((res) => { if (res.status === 200) { console.log("Submit successful"); } }).catch((err) => { console.log("Failed", err); }); } return ( <> <div> <h1>{user ? user : 'Not logged in'}</h1> </div> <hr /> <div className='image'> <form onSubmit={handleSubmit}> <input type='text' value={formData.name} placeholder='name' name='name' onChange={handleChange} /> <input type='text' value={formData.email} placeholder='email' name='email' onChange={handleChange} /> <input type='text' value={formData.number} placeholder='number' name='number' onChange={handleChange} /> {/* File input */} <input type='file' onChange={handleFile} /> {pre && <img src={pre} alt="Preview" style={{ width: '100px', height: '100px' }} />} <button type='submit'>Submit</button> </form> </div> </> ) } export default Private;
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: