首页 > 解决方案 > 提交带有文件输入和其他输入的表单

问题描述

我想上传一个包含其他表单数据的文件。但是当我上传具有不同路由的文件时,如 router.post(/api/upload)" 它可以工作,但我想将文件与其他表单数据一起上传到 route.post('/api/complaints') 等路由,但是当我使用 route.post('/api/complaints') 时,“req.file”是未定义的,但是当我使用 router.post(/api/upload) 时,它会被上传。请帮忙。

这是 multer 配置

const upload = multer({
  limits: {
    fileSize: 10000000
  },
  fileFilter(req, file, cb) {
    if (!file.originalname.match(/\.(jpg|jpeg|png)$/)) {
      return cb(new Error("File must be .jpg | .jpeg | .png"));
    }
    cb(undefined, true);
  }
});

这是上传文件的路径。

router.post(
  "/upload",
  upload.single("complaint"),
  async (req, res) => {
    // req.file.buffer;
    res.status(200).send("file uploaded successfully." + req.file.buffer);
  },
  (error, req, res, next) => {
    res.status(400).send({ error: error.message });
  }
);

这是发布所有表单数据的路径。问题就在这里。这里 req.file 是未定义的。

router.post(
  "/",
  authComplainer,
  upload.single("complaint"),
  async (req, res) => {

    const category = await Category.findById(req.body.categoryId);

    if (!category) return res.status(400).send("Invalid category.");

    const assignee = await Assignee.findOne({
      responsibility: category
    });
    if (!assignee) return res.status(400).send("Invalid Assignee.");

    const complainer = await Complainer.findById(req.complainer._id);
    if (!complainer) return res.status(400).send("Invalid Complainer.");

    let complaint = new Complaint({
      category: {
        _id: category._id
      },
      complainer: {
        _id: complainer._id
      },
      assignedTo: {
        _id: assignee._id
      },
      geolocation: req.body.geolocation ? req.body.geolocation : "",
      details: req.body.details,
      title: req.body.title,
      location: req.body.location,
      image: req.file ? req.file.buffer : ""
    });

    await complaint.save();
    res.send(complaint);

这是我的 reactjs 代码

 handleFileChange = e => {
    // if (this.checkMimeType(e)) {
    this.setState({ selectedFile: e.target.files[0] });
}

doSubmit = async () => {
    this.setState({ isDialogOpen: false });
    this.setState({ isLoading: true });

    const data = new FormData();
    data.append(
      "complaint",
      this.state.selectedFile,
      this.state.selectedFile.name
    );

    const newState = { ...this.state.data, data };
    console.log(newState);

    const { data: result } = await saveComplaint(this.state.data);
    this.setState({ isLoading: false });

    console.log(result);
    toast.success("Complaint is successfully registered.");
    // this.props.history.replace("/complainer");
   };

我想上传文件以及其他表单数据,如输入类型文本等,但它不起作用。请帮忙。主要问题出在React.js代码中。从 React 应用程序发送时 req.file 未定义。当我从 Postmon 测试它时。它适用于两种情况

标签: node.jsreactjsfilefile-uploadmulter

解决方案


所以,如果你已经确定了“React.js 中的问题”,那么请在 React 的 github 中提交问题!


推荐阅读