3

嘿,所以我试图接受上传的文件,但每次我调用 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")
4

3 回答 3

10

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

于 2013-11-13T17:06:56.553 回答
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

于 2013-11-15T08:46:45.693 回答
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

于 2014-02-03T17:35:36.313 回答