req.files not working node.js - express

时光毁灭记忆、已成空白 提交于 2019-12-20 02:37:05

问题


Hey so I am trying to accept an uploaded file but everytime I call req.files it is considered undefined... Not sure what I am doing wrong...

This is my app.js file:

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);

Then in my routes file I am just calling

req.files

and on the client side I am calling:

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")

回答1:


You need to add enctype="multipart/form-data" to the form




回答2:


Besides what @Jani said, you have an error in your app:

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

This basically translates to:

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

So no need for the last multipart middleware.

Docs:

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




回答3:


Instead of calling express.bodyParser() consider the alternatives mentioned here: https://github.com/senchalabs/connect/wiki/Connect-3.0

In my case, as Connect will remove multipart middleware compatibility, a warning appears every time I start node server.

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

I've tested connect-multiparty and req.files is initialized fine. https://github.com/andrewrk/connect-multiparty



来源:https://stackoverflow.com/questions/19959708/req-files-not-working-node-js-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!