我的应用程序中的教练可以为他的个人资料,客户,计划和锻炼上传图像。
上传文件后,nodejs服务器将其重命名。然后nodejs服务器需要根据发送图像的表单(注册,编辑用户,添加客户端,编辑客户端等等)插入/更新数据库上的图像名称。
因此我想将更多数据/参数发送到nodejs函数。
HTML:
<form name="userUpdateForm" action="/university/uploadImage" method="post" enctype="multipart/form-data" id="editUserForm">
<label>Replace Logo Image</label></br>
<input id="uploadFile" name="filetoupload" type="file">
<input type="submit">
</form>
节点:
router.post('/uploadImage', function (req,res,next) {
var newpath = "";
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
var oldpath = files.filetoupload.path;
var time = new Date();
var newImageName = time.getHours() + "-" + time.getMinutes() + "-" + time.getSeconds() + "-" + files.filetoupload.name;
newpath = './uploaded/' + newImageName;
//sendToDbImageName(newImageName);
fs.readFile(oldpath, function (err, data) {
if (err) throw err;
console.log('File read!');
// Write the file
fs.writeFile(newpath, data, function (err) {
if (err) throw err;
console.log('File uploaded and moved!');
console.log('File written!');
res.redirect(url + '?uid=' + globalUid + '#/editUser');
});
// Delete the file
fs.unlink(oldpath, function (err) {
if (err) throw err;
console.log('File deleted!');
});
});
});
});
更新 这就是我解决这个问题的方法:
一个从不同形式(教练,客户,程序,练习)获取图像的函数,生成唯一的文件名,并插入/更新数据库。
不要重复;校验, 不要再去服务器两次;校验, 上传文件后防止重定向;检查。
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, __dirname + '/../uploaded')
},
filename: function (req, file, cb) {
var time = new Date();
cb(null, time.getHours() + "-" + time.getMinutes() + "-" +
time.getSeconds() + "-" + file.originalname) //Appending extension
}
})
var upload = multer({ storage: storage });
router.post('/uploadImage', upload.single('avatar'), function (req, res, next) {
var formName = req.body.formName;
switch (formName) {
case "editUser":
var sql = "UPDATE coachdirectory SET logo = '" + req.file.filename + "' WHERE uid = '" + req.body.uid + "'";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result.affectedRows + " record(s) updated");
});
res.redirect(url + '/?uid=' + req.body.uid + '#/yourClients');
break;
case "registerUser:
other business logic
break;
}
});