var express = require('express');
var router = express.Router();
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/uploads/');
},
filename: function (req, file, cb) {
cb(null, file.originalname);
}
});
var upload = multer({
storage: storage, fileFilter: function (req, file, cb) {
if (file.mimetype !== 'image/png' && file.mimetype !== 'image/jpg' && file.mimetype !== 'image/jpeg') {
return cb(null, false);
}
return cb(null, true);
}
}).any();
/* get home page. */
router.get('/', function (req, res) {
res.render('index', { title: 'express' });
});
router.post('/', function (req, res) {
upload(req, res, function (err) {
if (err) {
//I want to jump to another page
} else {
res.send(req.files);
}
});
});
module.exports = router;
如果(错误)条件我想重定向我在views文件夹下创建的页面,则称其为错误。但是,如果我使用res.redirect('wrong')或res.redirect('views / wrong'),它们就不起作用了。实际上我尝试了很多方法,但所有方法都没有用。如果我上传文件而不是图片,它将跳转到一个带有'[]'的页面。我该怎么做重定向?
答案 0 :(得分:0)
您可以使用以下内容:
router.post('/', function (req, res) {
upload(req, res, function (err) {
if (err) {
res.redirect('/?error=upload_error');
} else {
res.send(req.files);
}
});
});
在页面中使用upload_error
来显示错误。
答案 1 :(得分:0)
我有另一种选择。在这种情况下,如果您上传错误的类型文件,它可能会显示错误的消息。
var express = require('express');
var router = express.Router();
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/uploads/');
},
filename: function (req, file, cb) {
cb(null, file.originalname);
}
});
var upload = multer({
storage: storage, fileFilter: function (req, file, cb) {
if (file.mimetype !== 'image/png' && file.mimetype !== 'image/jpg' && file.mimetype !== 'image/jpeg') {
req.fileValidationError = 'goes wrong on the mimetype';
return cb(null, false, new Error('goes wrong on the mimetype'));
}
return cb(null, true);
}
}).any();
/* get home page. */
router.get('/', function (req, res) {
res.render('index', { title: 'express' });
});
router.post('/', function (req, res) {
upload(req, res, function (err) {
if (req.fileValidationError) {
//I want to jumpt to another page
res.send("You didn't upload a valid pic");
} else {
res.send(req.files);
}
});
});
module.exports = router;