Uploading image in backend using "content-type":"multipart/formdata"

971 Views Asked by At

On postman,everything works fine,i get desired image URL there from Amazon S3,but when I try the same through front end I get error "Error: Multipart: Boundary not found". Then if I add some boundary it gives error TypeError: Cannot read property 'location' of undefined

Can anyone help with it?I just don't understand what's the problem here as everything works on postman..

const onSave = async (image) => {
  const data = new FormData();
  data.append("image", image);
  console.log(data);
  await dispatch(profileActions.changeImage(data, token));
};

//req payload

const response = await fetch(`${url}/images/image-upload`, {
    method: "POST",
    headers: {
      "Content-Type": "multipart/form-data;boundary=----------sdnasiuzasax",
      // "Content-Type": "application/json",
      // boundary: "???",
      "x-auth-token": token,
      // enctype: "multipart/form-data",
    },
    body: file,
  });
  const responseJson = await response.json();
  console.log(responseJson);

//backend

const upload = multer({
  limits: { fieldSize: 25 * 1024 * 1024 },
  storage: multerS3({
  s3: s3,
  bucket://bucket name
  acl: "public-read",
  metadata: function (req, file, cb) {
  cb(null, { fieldName: "Testing meta data" });
  },
  key: function (req, file, cb) {
  cb(null, Date.now().toString());
  },
}),

});

router.post("/image-upload", auth,upload, async (req, res, next) => {
const token = req.header("x-auth-token");
const { _id } = req.user;
try {
  let user = await User.findByIdAndUpdate(_id, {
    $set: {
      imageURL: req.file.location,
    },
  });
  if (!user) {
    return res
      .status(404)
      .send({ Error: "User with given id was not found!" });
    }

  return res.status(200).send({ details: details, token: token });

} catch (err) {
  console.log(err);
  return res.status(505).send({ Error: "Something went wrong" });
}

});

1

There are 1 best solutions below

1
On

I think that you are using multer in the wrong way. Middleware should be like this

router.post("/image-upload", auth, upload.single("location"), async (req, res, next) => {