2

There is something wrong in my source code but I'm not able to figure out what - please help. I was looking for some solutions found some and updated source code according them but didn't help.

var express = require('express');
var fs = require('fs');
var bodyParser  = require('body-parser');
var app = express()

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

var form = "<!DOCTYPE HTML><html><body>" +
"<form method='post' action='/upload' enctype='multipart/form-data'>" +
"<input type='file' name='image' id='image'/>" +
"<input type='submit' /></form>" +
"</body></html>";



app.get('/', function(req, res){
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(form);

});

app.post('/upload', function(req, res){
    fs.readFile(req.files.image.path, function(err, data){

        var imageName = req.files.image.name
        if(!imageName){
            console.log("There was an error");
            res.redirect('/');
            res.end();
        }else{
            var newPath = __dirname + "/uploads/fullsize/" + imageName;

            fs.writeFile(newPath, data, function(err){
                res.redirect("/uploads/fullsize/" + imageName);
            });
        }

    });
});

app.listen(8080);
Jordonias
  • 5,510
  • 2
  • 19
  • 31
Robert
  • 1,202
  • 4
  • 18
  • 35
  • try `req.body.files` instead of `req.files`. If you're sending some data from an HTTP request it would be stored in the request body. http://stackoverflow.com/questions/11625519/how-to-access-the-request-body-when-posting-using-node-js-and-express – Cory Danielson Aug 26 '14 at 20:43
  • Same problem still - when I have put on console req.body it's empty. Please note that it's multipart not json. – Robert Aug 26 '14 at 20:44

1 Answers1

4

The body-parser middleware does not handle multipart bodies.

From the body-parser github:

This does not handle multipart bodies, due to their complex and typically large
nature. For multipart bodies, you may be interested in the following modules:

https://github.com/expressjs/body-parser

Jordonias
  • 5,510
  • 2
  • 19
  • 31