【发布时间】:2021-08-29 13:43:03
【问题描述】:
我想使用 axios 将 formData 发布到节点 js 路由,然后将图像文件保存到 images 文件夹中。我正在使用 multer 从 axios 读取多部分/表单数据。我从 req.body 接收到 productInfo 对象,这是正确的。这是我的代码:
const addNewProduct = () => {
const newProduct = {
name: name,
cost: cost,
size: size,
color: color,
material: material,
discount: discount,
description: description,
category: category
};
const nulls = Object.values(newProduct).filter(p => p === null);
if(nulls.length === 0 && images.imageFiles) {
let productFormData = new FormData();
productFormData.append('productInfo', JSON.stringify(newProduct));
productFormData.append('productImages', [...images.imageFiles]);
const addUrl = "http://localhost:8080/cpnl/addproduct";
axios({
method: "POST",
url: addUrl,
data: productFormData,
headers: { "Content-Type": "multipart/form-data" }
})
.then((response) => {
console.log(response.data.msg);
})
.catch((response) => {
console.error(response);
});
}else {
Notiflix.Notify.Warning("Check your inputs!");
console.log(nulls);
console.log("product: \n" + JSON.stringify(newProduct));
}
};
然后我使用 multer 在节点 js 中接收数据,如下所示:
multer 配置:
const storage = multer.diskStorage({
destination: "./public/images",
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
const upload = multer({
storage: storage,
limits:{fileSize: 1000000},
fileFilter: function(req, file, cb){
checkFileType(file, cb);
}
}).array("productImages");
function checkFileType(file, cb) {
// Allowed ext
const filetypes = /jpeg|jpg|png/;
// Check ext
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
// Check mime
const mimetype = filetypes.test(file.mimetype);
if(mimetype && extname){
return cb(null,true);
} else {
cb('Error: Images Only!');
}
}
多路路由:
router.post('/addproduct', async (req, res) => {
upload(req, res, (err) => {
if(err) {
res.status(400).json({
msg: err
});
} else {
if(req.files == undefined) {
res.status(400).json({
msg: "Error: No file selected! please contact the developer."
});
} else {
//problem occures here
console.log( "images: " + req.body.productImages + "\n");
data = req.body.productInfo;
res.status(200).json({
msg: "Files uploaded!"
});
console.log("data" + data);
}
}
});
});
我在 req.body.productImages 中接收图像文件作为对象文件。
所有这些代码起初看起来都不错,但 multer 没有上传图像文件!
为什么图像在 req.body.productImages 中?
为什么它们不在 req.files 中?
这里发生了什么?
【问题讨论】:
标签: node.js reactjs axios multer