[英]Unable to use filefilter to redirect other page in express js
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;
In if (err) condition I want to redirect the page I created under views folder, its's called wrong. 在if(err)条件下,我想重定向在views文件夹下创建的页面,这被称为错误。 However, if I use res.redirect('wrong') or res.redirect('views/wrong'), they just didn't work.
但是,如果我使用res.redirect('wrong')或res.redirect('views / wrong'),它们只是无法工作。 Actually I tried a lot of methods but all of them didn't work.
实际上,我尝试了很多方法,但所有方法均无效。 If I upload the file but not a picture, it will jump to a page with one '[]' in it.
如果我上传文件而不上传图片,它将跳到其中包含一个[[]]的页面。 How can I do redirect?
我该如何重定向?
You could use something like this: 您可以使用如下形式:
router.post('/', function (req, res) {
upload(req, res, function (err) {
if (err) {
res.redirect('/?error=upload_error');
} else {
res.send(req.files);
}
});
});
Use upload_error
in your page to show the error. 在页面中使用
upload_error
显示错误。
I get an alternative. 我有一个选择。 In this case it can show the wrong message if you upload wrong type file.
在这种情况下,如果您上传错误的类型文件,它可能会显示错误的消息。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.