Cannot read property ‘path’ of undefined while uploading image upload on the frontend(react)

Tags: , , , ,



I am trying to upload an image on the frontend, but this is not working, I am getting the error below

message: "Cannot read property 'path' of undefined"
status: "fail"

When I log req.file on the backend and try to upload on the frontend, I get undefined in the console, but this gets logged for req.body

[Object: null prototype] {
  name: 'sfdgg',
  description: 'dsfdgg',
  reviewImage: '[object Object]' }

Image upload works fine on the backend via Postman.

Here is the frontend logic

const formData = new FormData();

for (let key in review) {
  formData.append(key, review[key]);
}

formData.append("reviewImage", reviewImage)

console.log(reviewImage)

axios.post("http://localhost:3001/api/v1/reviews", formData,{
    headers: {
        "content-type": "multipart/formdata"
    }
})

Removing the content-type doesn’t work, as it does not work with the content-type as well.

Multer config

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 1024 * 1024 * 5,
  },
  fileFilter: fileFilter,
});

upload.single("reviewImage");

Seen similar questions, but the answers do not work for me, kindly assist.

Answer

Try this for adding file in form data

var formData = new FormData();
var imagefile = document.querySelector('#reviewImage');
formData.append("reviewImage", imagefile.files[0]);
axios.post("http://localhost:3001/api/v1/reviews", formData, {
    headers: {
        "content-type": "multipart/formdata"
    }
})


Source: stackoverflow