【问题标题】:MEAN stack multer image upload unexpected field errorMEAN堆栈多图上传意外字段错误
【发布时间】:2021-02-05 07:20:49
【问题描述】:

我正在尝试通过 multer 将文件上传到服务器,即使每个文件名字段都相同,我也会不断收到 Unexpected field 错误。我不知道什么可能导致问题。也许有人可以帮忙?

错误信息: Error massage

所以这些是我的相关代码:

创建从 html 页面获取图像的 formGroup。

在upload-property.component.ts中

this.imageForm = new FormGroup({
        description: new FormControl(null),
        image: new FormControl(null, {
          asyncValidators: [mimeType]
        })
      })

这是组件 ts 文件中带有 onSaveProperty 函数的 onImagePicked 函数。

onImagePicked(event: Event) {
      const file = (event.target as HTMLInputElement).files[0];
      this.imageForm.patchValue({ image: file });
      console.log("picked");
      this.imageForm.get("image").updateValueAndValidity();
      const reader = new FileReader();
      reader.onload = () => {
        this.imagePreview = reader.result as string;
      };
      reader.readAsDataURL(file);
}
    
onSaveProperty() {
      if (this.typeForm.invalid || this.addressForm.invalid || this.datasForm.invalid || this.optionalForm.invalid || this.imageForm.invalid ) {
        console.log("invalid form");
      }
      console.log("Not invalid");
      this.isLoading = true;
      if (this.mode === "create") {
        console.log("entered here");
        this.propertyService.addProp(
          this.typeForm.value.type,
          this.addressForm.value.city,
          this.addressForm.value.city2,
          this.addressForm.value.address,
          this.datasForm.value.size,
          this.datasForm.value.price,
          this.datasForm.value.numberOfRooms,
          this.datasForm.value.condition,
          this.datasForm.value.year,
          this.datasForm.value.heatingType,
          this.optionalForm.value.level,
          this.optionalForm.value.parking,
          this.optionalForm.value.elevator,
          this.optionalForm.value.garden,
          this.optionalForm.value.attic,
          this.optionalForm.value.pet,
          this.optionalForm.value.smoke,
          this.optionalForm.value.furnitured,
          this.imageForm.value.image,
          this.imageForm.value.description
        );
        console.log("after addprop");
      } else {
        this.propertyService.updateProp(
          this.prop.id,
          this.typeForm.value.type,
          this.addressForm.value.city,
          this.addressForm.value.city2,
          this.addressForm.value.address,
          this.datasForm.value.size,
          this.datasForm.value.price,
          this.datasForm.value.numberOfRooms,
          this.datasForm.value.condition,
          this.datasForm.value.year,
          this.datasForm.value.heatingType,
          this.optionalForm.value.level,
          this.optionalForm.value.parking,
          this.optionalForm.value.elevator,
          this.optionalForm.value.garden,
          this.optionalForm.value.attic,
          this.optionalForm.value.pet,
          this.optionalForm.value.smoke,
          this.optionalForm.value.furnitured,
          this.imageForm.value.image,
          this.imageForm.value.description
        );
      }
      console.log("before reset");
      this.addressForm.reset();
      this.datasForm.reset();
      this.optionalForm.reset();
      this.imageForm.reset();
      this.typeForm.reset();
    }
  }

在 property.service.ts 上:

addProp(type: string, city: string, city2: string, address: string,  size: number, price: number, condition: string, year: number,
    numberOfRooms: number, parking: string, furnitured: boolean, garden: boolean, attic: boolean, pet: boolean, smoke: boolean,
    heatingType: string, elevator: boolean, description: string, level: number, image: File
    ) {
      console.log("INADDPROP");
      const propData = new FormData();
      propData.append("city", city);
      propData.append("city2", city2);
      propData.append("address", address);
      propData.append("condition", condition);
      propData.append("price", price as unknown as string);
      propData.append("year", year as unknown as string);
      propData.append("numberOfRooms", numberOfRooms as unknown as string);
      propData.append("garden", garden as unknown as string);
      propData.append("attic", attic as unknown as string);
      propData.append("heatingType", heatingType);
      propData.append("size", size as unknown as string);
      propData.append("elevator", elevator as unknown as string);
      propData.append("level", level as unknown as Blob);
      propData.append("furnitured", furnitured as unknown as Blob);
      propData.append("pet", pet as unknown as Blob);
      propData.append("smoke", smoke as unknown as Blob);
      propData.append("parking", parking);
      propData.append("description", description);
      propData.set("image", image);
      propData.append("type", type);
    this.http
      .post(
        this.url,
        propData
      )
      .subscribe(responseData => {
        this.router.navigate(["/"]);
      });
  }

关于服务器端代码:

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const isValid = MIME_TYPE_MAP[file.mimetype];
    let error = new Error("Invalid mime type");
    if (isValid) {
      error = null;
    }
    cb(error, "backend/images");
  },
  filename: (req, file, cb) => {
    const name = file.originalname
      .toLowerCase()
      .split(" ")
      .join("-");
    const ext = MIME_TYPE_MAP[file.mimetype];
    cb(null, name + "-" + Date.now() + "." + ext);
  }
});
const upload = multer({storage: storage});
router.post(
  "",
  checkAuth,
  upload.single('image'),
  (req,res,next) => {
    const url = req.protocol + "://" + req.get("host");
    const prop = new Property({
      city: req.body.city,
      city2: req.body.city2,
      address: req.body.address,
      type: req.body.type,
      size: req.body.size,
      condition: req.body.condition,
      price: req.body.price,
      year: req.body.year,
      parking: req.body.parking,
      numberOfRooms: req.body.numberOfRooms,
      furnitured: req.body.furnitured,
      elevator: req.body.elevator,
      level: req.body.level,
      garden: req.body.garden,
      attic: req.body.attic,
      pet: req.body.pet,
      smoke: req.body.smoke,
      heatingType : req.body.heatingType,
      creator: req.userData.userId
  //    image: url + "/images/" + req.file.filename
    });
    prop.save().then(updatedProperty => {
      console.log(updatedProperty);
      res.status(201).json({
        message: "Post added successfully",
        prop: {
          ...updatedProperty,
          id: updatedProperty._id
        }
      });
    });
  }
);

就是这样。我真的很绝望,我几天来一直在寻找解决方案,但到目前为止我一无所获。非常感谢任何帮助。

【问题讨论】:

  • 我可以建议发布错误堆栈而不是所有源代码。
  • 没错,我编辑了。

标签: javascript node.js angular mean-stack multer


【解决方案1】:

Content-Type 标头设置为multipart/form-data

【讨论】:

    【解决方案2】:

    由于您的代码看起来没问题(upload.single('image') 与表单数据中的图像名称匹配),可能是 checkAuth 或其他中间件已经使用了请求负载。如果是这种情况,那么流中将没有任何东西可供 multer 使用。

    尝试禁用 checkAuth 或之前的其他中间件以找出罪魁祸首。

    【讨论】:

    • 我确实禁用了 checkAuth 中间件,但它是一样的。 ://
    • 在此之前没有其他中间件吗?您是否也尝试过通过邮递员/curl 提出请求?
    猜你喜欢
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多