使用“ content-type”:“ multipart / formdata”在后端上传图像

问题描述

在邮递员上,一切正常,我从Amazon S3那里获得了所需的图像URL,但是当我在前端尝试相同的操作时,出现错误错误:多部分:未找到边界”。 然后,如果我添加一些边界,则会出现错误TypeError:无法读取未定义的属性“位置”

有人可以帮忙吗?我只是不明白这里的问题是什么,因为一切都在邮递员上进行。

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

//要求有效载荷

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);

//后端

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,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" });
}

});

解决方法

我认为您使用错误的multer。 中间件应该是这样的

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