0
votes

I am unable to upload the image file to the backend. Upon consoling inside action creator "profileAdd" (console.log(formData))which is coming from frontend onSubmit() ,everything seems fine, I mean all the fields and image file is getting printed on console but after making a axios post request, Almost everything goes to the backend except image file.

ProfileCreate.js component file

import React, { Component } from 'react';
import '../App.css';
import {connect} from 'react-redux';
import {profileAdd} from '../actions/profile';
import { withRouter } from 'react-router-dom';

class ProfileCreate extends Component {
   constructor(props){
      super(props);
      this.state = {
         image : null
      }
   }

   fileSelectedHandler = (e) => {
      this.setState({ image: e.target.files[0] });
      // console.log(e.target.files[0]);
   }

   onSubmit = (e) => {
   e.preventDefault();
   //Getting the values
   const firstName = this.inpFirstname.value;
   const lastName = this.inpLastname.value;
   const emailId = this.inpemail.value;

   let fd = {
      firstName,
      lastName,
      emailId,
      productImage: this.state.image
   };
   this.props.profileAdd(fd, this.props.history);
 }
 render() {
  return (
   <form name="profileCreate" className="profile-form" onSubmit={e => this.onSubmit(e)}>
      <div className="form-control">
         <label htmlFor="firstName">First Name</label><br/>
         <input type="text" id="firstName" name="firstName" placeholder="First Name" ref ={input => this.inpFirstname = input} />
      </div>

      <div className="form-control">
         <label htmlFor="LastName">Last Name</label><br/>
         <input type="text" id="LastName" name="lastName" placeholder="Last Name" 
               ref ={input => this.inpLastname = input}/>
      </div>

      <div className="form-control">
         <label htmlFor="prodImage">Product Image</label><br/>
         <input type="file" id="prodImage" name="prodImage" onChange={this.fileSelectedHandler} />
      </div>

      <div className="form-control">
         <label htmlFor="email">Email</label><br/>
         <input type="email" id="email" name="email" ref ={input => this.inpemail = input} />
      </div>

      <div className="form-action">
         <input type="submit" value="Click here"  />
      </div>

   </form>
  )
 }
}
export default connect(null, {profileAdd})(withRouter(ProfileCreate));


// profile create action creator
export const profileAdd = (formData, history) => async dispatch => {
    console.log(formData); // showing form fields and image till here
     const config = {
        headers : { 'Content-Type': 'application/json' }
      };

     try {
       await api.post('/api/profile/create', formData, config);
       dispatch({ type: 'CREATE_PROFILE', payload: formData });
       history.push('/list')
     } catch (error) {
      console.log(error);
     }
}

ProfileReducer file
====================

const initialState = {
   profiles:[],
   profile:{}
};

export default (state = initialState, action) => {
 switch (action.type) {
  case 'CREATE_PROFILE':
     return {...state, profiles: [...state.profiles, action.payload]};

  case 'GET_PROFILE':
       return {...state, profiles: action.payload};

  default:
     return state;
 }

};


Kindly tell me what is going wrong with the code. When I am making a post request through POSTMAN then image is getting uploaded in the backend.But not from the frontend.

1
Sending image through Content-Type: application/json might not work.Rohit Kashyap
But on the POSTMAN i am sending through Content-Type: application/json and its working perfectlyarjun sah

1 Answers

1
votes

The thing was we need to upload files through javascript new FormData() object only. The above code in ProfileCreate.js component::

let fd = {
    firstName,
    lastName,
    emailId,
    productImage: this.state.image
};

is replaced by:

`const fd = new FormData();
   fd.append('productImage', productImage);
   fd.append('firstName', firstName);
   fd.append('lastName', lastName);
   fd.append('emailId', emailId);
`

and file will upload perfectly.