1

I am trying to upload an image from my front end to the backend but it it doesn't send the image in the request

It says that the formdata is empty and it says that there's no image found, where is the problem and how can I fix this error?

Here is the code from the Frontend made in react:

const [userInfo, setuserInfo] = useState({
    file:[],
    filepreview:null,
   });

  const handleInputChange = (event) => {
    setuserInfo({
      ...userInfo,
      file:event.target.files[0],
      filepreview:URL.createObjectURL(event.target.files[0]),
    });

  }

  const [isSucces, setSuccess] = useState(null);

  const submit = async () =>{
    const formdata = new FormData(); 
    formdata.append('avatar', userInfo.file);
    console.log(formdata)

    Axios.post("http://localhost:4000/imageupload", formdata,{   
            headers: { "Content-Type": "multipart/form-data" } 
    })
    .then(res => { // then print response status
      console.warn(res);
      if(res.data.success === 1){
        setSuccess("Image upload successfully");
      }

    })
  }

The code of the Backend made in NodeJS:

const storage = multer.diskStorage({
    destination: path.join(__dirname, './temp', 'uploads'),
    filename: function (req, file, cb) {   
        // null as first argument means no error
        cb(null, Date.now() + '-' + file.originalname )  
    }
})

app.post('/imageupload', async (req, res) => {  
    try {
        // 'avatar' is the name of our file input field in the HTML form

        let upload = multer({ storage: storage}).single('avatar');

        upload(req, res, function(err) {
            // req.file contains information of uploaded file
            // req.body contains information of text fields

            if (!req.file) {
                return res.send('Please select an image to upload');
            }
            else if (err instanceof multer.MulterError) {
                return res.send(err);
            }
            else if (err) {
                return res.send(err);
            }

            const classifiedsadd = {
                image: req.file.filename
            }; 
            res.send("ok")
        }); 

    }catch (err) {console.log(err)}
})

Edit: Output

warre
  • 33
  • 1
  • 8

1 Answers1

0

Multer is essentially a nodejs router,i.e. a function that can be pipelined between your HTTP request and HTTP response. I think that you should first make multer analyze your HTTP content and to actually populate the req.file before actually evaluate express parsers do their job.

const storage = multer.diskStorage({
    destination: path.join(__dirname, './temp', 'uploads'),
    filename: function (req, file, cb) {   
        // null as first argument means no error
        cb(null, Date.now() + '-' + file.originalname )  
    }
})

let upload = multer({ storage: storage});

app.post('/imageupload', upload.single('avatar'), async (req, res) => {  
    try {
        // 'avatar' is the name of our file input field in the HTML form
        // req.file contains information of uploaded file
        // req.body contains information of text fields

            if (!req.file) {
                return res.send('Please select an image to upload');
            }
            else if (err instanceof multer.MulterError) {
                return res.send(err);
            }
            else if (err) {
                return res.send(err);
            }

            const classifiedsadd = {
                image: req.file.filename
            }; 
            res.send("ok")

    }catch (err) {console.log(err)}
})

I am assuming that your upload code is working. Have you tried to read the HTTP request from your browser to see that the image has been correctly attached to the request? Because probably the issue lies in the fact that you are not actually parsing the image.

   const file = new File(userInfo.file, "avatar.png", {
        type: 'image/png' // choose the appropriate
    });
const formdata = new FormData(); 
    formdata.append('avatar', file);
console.log(formdata)
Thecave3
  • 762
  • 12
  • 27