首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >MEAN stack multer图像上载意外字段错误

MEAN stack multer图像上载意外字段错误
EN

Stack Overflow用户
提问于 2020-10-22 17:37:13
回答 2查看 80关注 0票数 1

我试图通过multer上传一个文件到服务器,但我不断收到意想不到的字段错误,即使每个文件名字段是相同的。我不知道是什么导致了这个问题。也许有人能帮上忙?

错误消息:Error massage

下面是我的相关代码:

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

在upload-property.component.ts中

代码语言:javascript
运行
复制
this.imageForm = new FormGroup({
        description: new FormControl(null),
        image: new FormControl(null, {
          asyncValidators: [mimeType]
        })
      })

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

代码语言:javascript
运行
复制
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上:

代码语言:javascript
运行
复制
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(["/"]);
      });
  }

在服务器端代码中:

代码语言:javascript
运行
复制
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
        }
      });
    });
  }
);

就是这样。我真的很绝望,我寻找了几天的解决方案,但到目前为止,我什么也没有得到。我真的很感谢你的帮助。

EN

回答 2

Stack Overflow用户

发布于 2020-10-22 17:49:15

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

票数 1
EN

Stack Overflow用户

发布于 2020-10-22 18:49:07

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

尝试禁用checkAuth或在其他中间件之前找到罪魁祸首。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64479459

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档