req.files not working node.js - express

2020-04-11 18:20发布

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

3条回答
迷人小祖宗
2楼-- · 2020-04-11 18:57

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

查看更多
够拽才男人
3楼-- · 2020-04-11 19:04

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

查看更多
小情绪 Triste *
4楼-- · 2020-04-11 19:16

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

查看更多
登录 后发表回答