0

I am using React and trying to send the form Input as well as a image file to a express server at a same time. I tried by appending these inputs data and file to the formData() and sending it to backend through axios post request, but the problem is : The form input given by user is perfectly going to express server but file is undefined in backend

My JSX

<form onSubmit={sendData}>
        <input value={data.productName} onChange={handleChange} type="text" name="productName" />
        <input value={data.productfeatures} onChange={handleChange} type="text" name="productfeatures" />

        <input onChange={imgChnage} type="file" name="test_files" />
        <button>Submit</button>
</form>

My function to handle input

const [data, setData] = useState({
    productName: "",
    productfeatures: "",
  })
  const { productName, productfeatures } = data;
  const [imgHolder, setImgHolder] = useState();
  const handleChange = (evt) => {
    const value = evt.target.value;
    setData({
      ...data,
      [evt.target.name]: value
    });
  }
  const imgChnage = (e) => {
    setImgHolder(e.target.files[0]);
  };
  console.log(imgHolder);
  const sendData = async (e) => {
    e.preventDefault();
    const fd = new FormData();
    fd.append('name', productName);
    fd.append('features', productfeatures);
    fd.append('image', imgHolder);
    try {
      await axios
        .post("http://localhost:3001/pnit/v1/api/product", fd)
    } catch (error) {
      console.log(error);
    }

All combined code

 import { useState } from "react";
    import axios from "axios";
    function App() {
      const [data, setData] = useState({
        productName: "",
        productfeatures: "",
      })

      const { productName, productfeatures } = data;
      const [imgHolder, setImgHolder] = useState();

      const handleChange = (evt) => {
        const value = evt.target.value;
        setData({
          ...data,
          [evt.target.name]: value
        });
      }


      const imgChnage = (e) => {
        setImgHolder(e.target.files[0]);
      };
      
      const sendData = async (e) => {
        e.preventDefault();
        const fd = new FormData();
        fd.append('name', productName);
        fd.append('features', productfeatures);
        fd.append('image', imgHolder);
        try {
          await axios
            .post("http://localhost:3001/pnit/v1/api/product", fd)
        } catch (error) {
          console.log(error);
        }
    
      }
    
      return (
        <>
          <form onSubmit={sendData}>
        <input value={data.productName} onChange={handleChange} type="text" name="productName" />
        <input value={data.productfeatures} onChange={handleChange} type="text" name="productfeatures" />

        <input onChange={imgChnage} type="file" name="test_files" />
        <button>Submit</button>
        </form> 
        </>
      );
    }
    
    export default App;
7
  • Axios is probably sending the wrong content-type header. Configure axios to send this header 'Content-Type': 'multipart/form-data'. Commented Mar 28, 2022 at 13:44
  • @morganney i tried by adding headers i.e 'Content-Type': 'multipart/form-data', but still a same problem ! Commented Mar 28, 2022 at 14:57
  • try changing form.append => fd.append Commented Mar 28, 2022 at 15:23
  • @traynor ohh my bad, but that's not a problem !! Commented Mar 29, 2022 at 8:15
  • @RajeshKhadka how are you handling request on the server Commented Mar 29, 2022 at 8:25

1 Answer 1

0

Hello developers, the problem is solved !!

Steps to solve a problem :

  1. install the dependency called express-fileupload inside server by the command npm i express-fileupload.

  2. import the express-fileupload at the main file of server.

  3. And finally, call the middleware app.use(fileupload());

Why the problem occured !:

Because, by default the req.files is undefined but calling the middleware at server, it parse the req.files and shows up the files sent from frontend.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.