[英]How to post form data ( image and data ) using MULTER, Nodejs and MySQL
I want to upload an image with a data on my form data using NodeJS, Multer and MySQL. 我想使用NodeJS,Multer和MySQL在表单数据上上传包含数据的图像。
As you can see below, my code : 如您在下面看到的,我的代码:
Table MySQL : 表MySQL:
CREATE TABLE produits (
Codep bigint(21) NOT NULL AUTO_INCREMENT,
Description varchar(100) COLLATE utf8_unicode_ci NOT NULL,
Img varchar(255) NOT NULL,
PRIMARY KEY (Codep )
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=10;
My router : 我的路由器:
const path = require('path');
const multer = require('multer');
const crypto = require('crypto');
const fs = require('fs');
var imge = "";
var storage = multer.diskStorage({
destination: function (req, file, cb){
cb(null, '../public/uploads')
},
filename: function (req, file, cb){
crypto.pseudoRandomBytes(32, function(err, raw){
imge = raw.toString('hex') + path.extname(file.originalname);
cb(null, imge);
})
}
});
var upload = multer({storage: storage});
exports.ajouterprod = function(req, res) {
console.log("req", req.body);
var today = new Date();
var produits = {
"Description": req.body.Description,
"Img": imge
}
upload.single('produits[Img]')
connection.query('INSERT INTO produits SET ?', produits, function(error, results, fields) {
if (error) {
console.log("error ocurred", error);
res.send({
"code": 400,
"failed": "error ocurred"
})
}
else {
res.send({
"code": 200,
"success": "produit registered sucessfully"
});
}
})
};
My server : 我的服务器:
router.post('/ajouterprod', produits.ajouterprod);
When I try that with Postman as you see below : 当我在Postman上尝试该操作时,如下所示:
I get : 我得到:
req {}
error ocurred { Error: ER_BAD_NULL_ERROR: Column 'Description' cannot be null
How can I fix that please ? 我该如何解决?
Your issue lies in req.body
. 您的问题在于
req.body
。 Because it's returning an empty object, the MySQL framework is trying to set Description to null, which is not valid. 因为它返回一个空对象,所以MySQL框架试图将Description设置为null,这是无效的。 Doing a
console.log(produits)
would reveal they're all null/undefined. 进行
console.log(produits)
会显示它们都是null / undefined。
I would suggest looking through this answer , as you need to use a body-parser that can handle file uploads. 我建议您仔细阅读此答案 ,因为您需要使用可以处理文件上传的正文解析器。
Additionally, it seems you're using multer wrong: 此外,您似乎在使用multer错误:
var upload = multer({storage: storage}).single('Img');
exports.ajouterprod = function(req, res) {
upload(req, res, function(imageUploadErr) {
console.log("req", req.body);
var today = new Date();
var produits = {
"Description": req.body.Description,
"Img": imge // (Wrong variable name, I think you want req.body.Img)
}
connection.query('INSERT INTO produits SET ?', produits, function(error, results, fields) {
if (error) {
console.log("error ocurred", error);
res.send({
"code": 400,
"failed": "error ocurred"
})
}
else {
res.send({
"code": 200,
"success": "produit registered sucessfully"
});
}
})
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.