Search code examples
node.jsreactjsmern

is there a way i can handle file upload in react


iam trying to submit these fields to node server from react i can submit rest of the input fields and select options but i cannot upload the photo plus i can upload all fields (including the photo) to the server using POSTMAN

 // fields to submit to node server
    state = {
        data: {
          fullName: '',
          email: '',
          phoneNumber: '',
          branchId: '',
          jobId: '',
          salary: '',
          image: '',
          // startDate: '',
        },
    
    // onChange handler
    
    handleChange = ({ currentTarget: input }) => {
        //clone the errors
        const errors = { ...this.state.errors }
        //validate the input
        const errorMessage = this.validateProperty(input)
        //
        if (errorMessage) errors[input.name] = errorMessage
        //
        else delete errors[input.name]
    
        //clone the data
        const data = { ...this.state.data }
    
        //override the state data with the input value
        data[input.name] = input.value
        // update the state with the data and errors
        this.setState({ data, errors })
      }
    // submit or onClick handler
    
    doSubmit = async () => {
        const { data } = this.state
    
        const fd = new FormData()
        fd.append('fullName', data.fullName)
        fd.append('email', data.email)
        fd.append('phoneNumber', data.phoneNumber)
        fd.append('branchId', data.branchId)
        fd.append('jobId', data.jobId)
        fd.append('salary', data.salary)
        fd.append('image', data.image)
    
        // fd.append()
    
        await saveEmployee(fd)
        this.props.history.push('/employees')
      }

Solution

  • I'm guessing that the image input is a file field?

    You are now storing the input#value of the file field but you're actually looking for the input#files[0] value. This contains the reference to the actual file and can be appended to the form.

    handleChange = ({ currentTarget: input }) => {
        //clone the errors
        const errors = { ...this.state.errors }
        //validate the input
        const errorMessage = this.validateProperty(input)
        //
        if (errorMessage) errors[input.name] = errorMessage
        //
        else delete errors[input.name]
    
        //clone the data
        const data = { ...this.state.data }
    
        //override the state data with the input value
        data[input.name] = input.type === 'file' ? input.files[0] : input.value
        // update the state with the data and errors
        this.setState({ data, errors })
      }