我是Node.js和表达框架的新手。
我想创建一个上传文件的服务,如果文件类型是图像,它将显示图像。如果文件不是图像,则假设向用户显示错误消息。我使用multer上传文件,如果文件扩展名与任何预定义的扩展名不匹配,它将返回false以停止上传过程。但不知何故,如果上传停止,它不会将页面重定向到错误页面。
返回false是否会停止整个POST过程?如果上传停止,有什么方法可以显示错误消息吗?
module.exports=function(app)
{
var express=require('express');
var multer=require('multer');
var path=require('path');
var fs=require('fs');
var bodyParser=require('body-parser');
var done = false;
var targetPath="";
app.use(bodyParser.urlencoded({uploadDir: '/uploads',extended:true, keepExtensions:true}));
app.use(function(req,res,next)
{
var handler = multer({ dest: './uploads/',
rename: function (fieldname, filename) {
return filename+Date.now();
},
onFileUploadStart: function (file) {
if(file.extension != 'png' && file.extension != 'jpg' && file.extension != 'jpeg' && file.extension != 'gif')
{
done = false;
return false;
}
console.log(file.originalname + ' is starting ...')
},
onFileUploadComplete: function (file) {
console.log(file.fieldname + ' uploaded to ' + file.path)
targetPath = file.path;
done = true;
}
});
handler(req, res, next);
});
app.get('/',function (req,res)
{
res.render('newindex.jade')
});
app.get('/errorpage', function (req,res)
{
res.render('errorpage.jade')
})
app.post('/uploads', function (req,res)
{
if(done = true)
{
console.log(req.files);
//res.end("Image has been uploaded at " + targetPath);
res.redirect("/" + targetPath);
targetPath="";
//res.send('<img src="' + targetPath + '">');
}
else
{
res.redirect("./errorpage")
}
});
app.get('/uploads/:file', function (req, res)
{
file = req.params.file;
var img = fs.readFileSync("./" + "/uploads/" + file);
res.writeHead(200);
res.end(img, 'binary');
});
}
答案 0 :(得分:0)
我认为您可以在onFileUploadStart()中添加req,res并在“return false;”行之前插入res.doSomething()。例如:
onFileUploadStart:function(file,req,res){
{ done = false; res.json({message: "Upload failed"}) return false; } console.log(file.originalname + ' is starting ...') }