前端 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未定义
您需要在表单中设置属性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 storage = multer.memoryStorage();
const uploadImage = multer({ storage: storage });
router.post("/create",uploadImage.single("myfile"),donationController.createDonatio);