req.files不工作node.js - express

时间:2013-11-13 16:53:09

标签: javascript node.js file-upload express pug

嘿所以我试图接受一个上传的文件,但每次我调用req.files它都被认为是未定义的......不确定我做错了什么......

这是我的app.js文件:

var express = require('express')
    , user = require('./routes/user')
    , http = require('http')
    , path = require('path')
    , mongoose = require('mongoose')
    , mongoConnect = mongoose.connect('mongodb://localhost/clothing')
    , app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser({uploadDir: './public/img'}));
app.use(express.multipart());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

app.get('/user', user.user);
app.post('/user', user.userPost);

然后在我的路线文件中,我只是在呼叫

req.files

在客户端我打电话:

form(action="/user", method="post")
        label name:
            input(type="text", name="name")
        label pic:
            input(type="file", name="picture", enctype="multipart/form-data")
        input(type="submit", value="Add New Clothes Item")

3 个答案:

答案 0 :(得分:9)

您需要将enctype="multipart/form-data"添加到表单

答案 1 :(得分:2)

除了@Jani所说的,你的应用中有错误:

app.use(express.bodyParser({uploadDir: './public/img'}));
app.use(express.multipart());

这基本上转化为:

app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart({uploadDir: './public/img'}));
app.use(express.multipart());

所以不需要最后的多部分中间件。

文档:

http://expressjs.com/api.html#bodyParser

答案 2 :(得分:1)

不要调用express.bodyParser()而是考虑这里提到的替代方案:https://github.com/senchalabs/connect/wiki/Connect-3.0

就我而言,由于Connect将删除多部分中间件兼容性,每次启动节点服务器时都会出现警告。

connect.multipart() will be removed in connect 3.0
visit https://github.com/senchalabs/connect/wiki/Connect-3.0 for alternatives
connect.limit() will be removed in connect 3.0

我测试了connect-multiparty,并且req.files初始化正常。 https://github.com/andrewrk/connect-multiparty