Node.js ReactJS上传文件到Express后端未定义
我正在尝试使用FormData从reactjs将profilePhoto上载到express后端:Node.js ReactJS上传文件到Express后端未定义,node.js,reactjs,express,multer,Node.js,Reactjs,Express,Multer,我正在尝试使用FormData从reactjs将profilePhoto上载到express后端: const form = new FormData(); form.append(user, "user"); form.append(profilePhoto, "profilePhoto"); axios({ method: "post", url: &q
const form = new FormData();
form.append(user, "user");
form.append(profilePhoto, "profilePhoto");
axios({
method: "post",
url: "http://localhost:8082/candidate/addCandidate",
data: form,
headers: { "Content-Type": "multipart/form-data" },
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
在后端:(这与邮递员配合得很好,图像被添加到后端)
const DIR=“/public/”
然而,当我试图上传一个文件时,它不会被上传到后端,我会得到req.file未定义的
。我试着去安慰req,这就是我得到的结果:
{'606aee02f057cd714db2b646':'user','[object File]:'profilePhoto'}
任何帮助 我认为您误用了formData.append,它应该是formData.append(“key”,value),所以在您的示例中:form.append(“user”,user)@Haythemfarhats天与这个问题斗争!你救了我。它起作用了
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, DIR);
},
filename: (req, file, cb) => {
const fileName = file.originalname.toLowerCase().split(" ").join("-");
cb(null, uuid() + "-" + fileName);
},
});
var upload = multer({
storage: storage,
fileFilter: (req, file, cb) => {
if (
file.mimetype === "image/png" ||
file.mimetype === "image/jpg" ||
file.mimetype === "image/jpeg"
) {
cb(null, true);
} else {
cb(null, false);
return cb(new Error("Only .png, .jpg and .jpeg format allowed!"));
}
},
});
router.post(
"/addCandidate",
upload.single("profilePhoto"),
(req, res, next) => {
const url = req.protocol + "://" + req.get("host");
// try {
const candidate = new Candidate({
user: req.body.user,
profilePhoto: url + "/public/" + req.file,
});
candidate
.save()
.then((result) => {
console.log("bbbbbbbbbbbb", req);
res.status(201).json({
message: "User registered successfully!",
profilePhoto: result.profilePhoto,
});
})
.catch((err) => {
console.log("aaaaaaaaaaaa", req.body.file);
res.status(500).json({ error: err });
console.log(err);
});
}
);