NodeJS 请求文件中的Buffer对象在express.js中未定义

pokxtpni  于 2023-10-17  发布在  Node.js
关注(0)|答案(1)|浏览(105)

frontend React.js中的表单。

const handleUpload = (e) => {
    setFormvalue({ ...formvalue, recevierImages: e.target.files[0] });
  };

  const submitData = () => {
    console.log(formvalue);
    dispatch(createDonation(getFormData(formvalue)));
  };

   <Form>
     <Form.Item name="donationImage" label="Upload Image">
        <input type="file" onChange={(e) => handleUpload(e)} />
      </Form.Item>
   </Form>
   <Button onClick={submitData} type="primary">
      Create
    </Button>

recevierImages是图像存储在react中的名称,单击submitData后,所有数据都会附加到FormData并发送到express js
后端express.js中的API

const express = require("express");
const multer = require("multer");

const donationController = require("../controller/donationController");

const router = express.Router();

const multerStorage = multer.diskStorage({
  destination: function (req, file, callBack) {
    callBack(null, "");
  },
});

const uploadImage = multer({ storage: multerStorage }).single("recevierImages");

router.post("/create", uploadImage, donationController.createDonation);
router.patch("/update", donationController.updateDonation);

module.exports = router;

donationController.js

const createDonation = async (req, res) => {
  try {
    console.log(req.file.buffer);
  } catch (error) {
    console.log(error);
    res.status(500).send(error);
  }
}

module.exports = {
  createDonation,
};

在donationController.js req.file.buffer中未定义

olmpazwi

olmpazwi1#

你需要在你的表单中设置属性enctype=“multipart/form-data”,因为你从你的react应用程序发送缓冲区,你最好使用memoryStorage而不是diskStorage和.single(),你需要传递你的字段名称。
在前端

<Form.Item> enctype="multipart/form-data" name="donationImage" label="Upload Image" action="#" method="post">
  <input type="file" onChange={(e) => handleUpload(e)} name="myfile" />
</Form.Item>

你的Express应用

const donationController = require("../controller/donationController");
const router = express.Router();
const storage = multer.memoryStorage();
const uploadImage = multer({ storage: storage });

router.post("/create",uploadImage.single("myfile"),donationController.createDonatio);

相关问题