0

I am trying to use it to send img to multer in node to upload the img but always get me a null

I tryed to restart the whole project but nothing

here front part :

const addPostsHundler = (e) => {
  e.preventDefault();

  const form = new FormData().append("file", file);

  console.log(data.user_id);

  axios
    .post("http://localhost:5000/Upload", {
      form: form,
      inputs: input,
      userID: data.user_id,
    })
    .then((res) => {
      console.log(res);
    })
    .catch((err) => console.log(err));
};

and back part :

const multer = require("multer");

let fileName;

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "../client/public/upload");
  },
  filename: function (req, file, cb) {
    fileName = file.originalname;
    cb(null, fileName);
  },
});

app.post("/Upload", upload.single("file"), (req, res) => {
  res.status(200).json({ message: "img stored", img: fileName });
});
Pluto
  • 4,177
  • 1
  • 3
  • 25

1 Answers1

0

I think you are passing form object to axios incorrectly. You need to pass form object directly because axios will automatically set the content-type header to multipart/form-data and include the boundary of the form object.

multer needs the content-type header to be multipart/form-data so it can read the form data properly on the backend. But if you put the form object inside another object, axios won't know that it's a form object and won't set the content-type header right. Then multer will get a blank or wrong form data on the backend.

For example:

const form = new FormData();
form.append("file", file);
form.append("inputs", input);
form.append("userID", data.user_id);

axios
  .post("http://localhost:5000/Upload", form) // pass form directly
  .then((res) => {
    console.log(res);
  })
  .catch((err) => console.log(err));
Pluto
  • 4,177
  • 1
  • 3
  • 25