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. However, if I use res.redirect('wrong') or res.redirect('views/wrong'), they just didn't work. 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.
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.