很多人会一步一步的跟着 Node.js实战那本书一起走,是的,一般情况下,我们会很顺利,但是有时候会很郁闷,比如 multer.
作者用的是 0.1.6,这个已经太老旧了,现在已经是 1.1.0了,当然你可以选择旧版本,但是作为我们这种程序员,怎么能停留了。
首先会报错
hrow new TypeError(‘app.use() requires middleware functions‘);
这个不碍事,我们百度,这有一个参考:http://segmentfault.com/q/1010000003050818?sort=created
我现在升级multer 1.1.0了,也碰到同样问题,然后去他的官网了解下。
已经不能这样写了
app.use(multer({dest:‘./‘}));
你要在路由里面写
var multer = require(‘multer‘);
var upload = multer({dest: ‘./public/images/user‘});
router.post(‘/upload‘, upload.fields([
{name: ‘file1‘},
{name: ‘file2‘},
{name: ‘file3‘},
{name: ‘file4‘},
{name: ‘file5‘}
]), function(req, res, next){
for(var i in req.files){
console.log(req.files[i]);
}
req.flash(‘success‘, ‘文件上传成功!‘);
res.redirect(‘/upload‘);
});
没错,我们在index.js应该是这样写的
var multer = require(‘multer‘); var upload = multer({dest: ‘./public/images/user‘}); app.post(‘/upload‘, upload.fields([ {name: ‘file1‘}, {name: ‘file2‘}, {name: ‘file3‘}, {name: ‘file4‘}, {name: ‘file5‘} ]), function(req, res, next){ for(var i in req.files){ console.log(req.files[i]); } req.flash(‘success‘, ‘文件上传成功!‘); res.redirect(‘/upload‘); });
是的,宝贝,你可以上传了,但是上传后生成的是随机生成的名字,这个不可以有,
参考官方文档:https://github.com/expressjs/multer
var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, ‘/tmp/my-uploads‘) }, filename: function (req, file, cb) { cb(null, file.fieldname + ‘-‘ + Date.now()) } }) var upload = multer({ storage: storage }) 再修改代码:
var multer = require(‘multer‘); var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, ‘./public/images/‘); }, filename: function (req, file, cb) { cb(null, file.originalname); } }) var upload = multer({ storage: storage }); app.post(‘/upload‘,checkLogin); app.post(‘/upload‘, upload.fields([ {name: ‘file1‘}, {name: ‘file2‘}, {name: ‘file3‘}, {name: ‘file4‘}, {name: ‘file5‘} ]), function(req, res, next){ for(var i in req.files){ console.log(req.files[i]); } req.flash(‘success‘, ‘文件上传成功!‘); res.redirect(‘/upload‘); });
亲,你就可以了,
版本啊,版本,切记,切记。
时间: 2024-11-05 17:41:08