NodeJs Multer错误

时间:2015-11-02 14:39:19

标签: node.js multer

我在尝试检索上传的文件时遇到了跟随错误。 我在网上搜索过,我发现的是人们将multer()的结果作为midleware注入,但我得到的只是错误......

/node_modules/express/lib/router/index.js:458
  throw new TypeError('Router.use() requires middleware function but got a
        ^
TypeError: Router.use() requires middleware function but got a Object
at Function.use (/node_modules/express/lib/router/index.js:458:13)
at EventEmitter.<anonymous> (/node_modules/express/lib/application.js:219:21)
at Array.forEach (native)
at EventEmitter.use (/node_modules/express/lib/application.js:216:7)
at Object.<anonymous> (/app.js:40:5)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)

以下是该应用程序部分的代码

var express = require('express');
var multer = require('multer');
var mul = multer({limits : {fileSize : 1000000, files : 10}});
var app = express();
var port = 3000;
var server = require('http');
app.use('/files', mul, files);
function files (req, res) {
  console.log(req.files, req.file);
}
server = server.createServer(app);
server.listen(process.env.PORT || port);

2 个答案:

答案 0 :(得分:2)

你有配置路由和multer的代码似乎有点不对劲。这就是它被描述为here的方式。 app.use中的第二个参数应为函数或函数 app.use docs,而代码中的mul Object ,结果为您在此处的配置工厂调用:var mul = multer({limits : {fileSize : 1000000, files : 10}});

//other stuff    
var mul = multer({limits : {fileSize : 1000000, files : 10}});

app.use('/files', [mul, files]);

function files (req, res) {
  console.log(req.files, req.file);
}
//other stuff

<强> UPD

根据模块页面上的文档,您是否尝试过这样做?

var mul = multer({ dest: 'your_uploads_path/' });
app.use('/files', mul.array(), files); //or other option 

其他选项在这里:https://www.npmjs.com/package/multer#multer-opts

<强> UPD2

According to docs multer确实会返回busboy应该使用的对象,因此您需要对其进行处理 - https://github.com/mscdex/busboy#busboy-methods

答案 1 :(得分:1)

这是有效的代码,感谢@shershen

//other stuff    
var mul = multer({limits : {fileSize : 1000000, files : 10}});
app.use('/files', mul.any(), files);
function files (req, res) {
console.log(req.files, req.file);
}
//other stuff