Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In express.js, req.files is undefined

I try to upload a png to my node.js server, but every time req.files.avatar is called, an error appears and says TypeError: Cannot read property 'avatar' of undefined.

like image 969
MrMangado Avatar asked Dec 23 '12 19:12

MrMangado


2 Answers

The problem was that I haven't write enctype="multipart/form-data"in the form. That's why req.files was undefined.

like image 194
MrMangado Avatar answered Nov 08 '22 23:11

MrMangado


Also I think you have to include your bodyParser before any instructions to use app.router or static middleware. After some trial and error this is the order that works for me.

app.configure(function(){
    app.set('port', process.env.port || 3000);
    app.set('views', __dirname + '/app/server/views');
    app.set('view engine', 'jade');
    app.locals.pretty = true;
    app.use(express.favicon());
    app.use(express.bodyParser( { keepExtensions: true, uploadDir: __dirname + '/app/uploads' } ));
    app.use(express.methodOverride());
    app.use(express.cookieParser());
    app.use(express.session({ secret: 'super-duper-secret-secret' }));
    app.use(app.router);
    app.use(require('stylus').middleware({ src: __dirname + '/app/public' }));
    app.use(express.static(__dirname + '/app/public'));
});
like image 16
braitsch Avatar answered Nov 09 '22 00:11

braitsch