Gil
Gil

Reputation: 97

req.files is empty when trying to upload a file to server with node js

HTML:

<form action="/uploadpic" method="post" enctype="multipart/form-data">
    <input type="file" data-clear-btn="true" name="image" id="new_pic" value="" placeholder="Choose File">
    <input type="submit" value="Add" style="width:30%">
</form>

NodeJS:

app.post('/uploadpic', function(req,res) {
console.log(req.files);
console.log(req.body);});

I also use:

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded());
app.use(bodyParser.json())
app.use(express.bodyParser({uploadDir:'./uploads'}));
app.use(bodyParser.json({ type: 'application/vnd.api+json' }))

in the console I get:

{}
{}

i dont seem to understand what could be the problem here.. thanks !

Upvotes: 0

Views: 2631

Answers (2)

kannanfa
kannanfa

Reputation: 100

   var fs = require('fs');

    app.post('/uploadpic', function(req,res) {

    //req.files contains array of files iterate and get it
    //if it has only one. it is like object

    //here is the code for object

    if (req && req.files) {

     var contentType = req.files.file.type;    
     var fname = req.files.file.name;    
     var image_path = req.files.file.path;    
     fs.readFile(image_path, function (err, data) { 
      var data = data; //this is your data use this
     })

    }

})

Upvotes: 1

Ben Fortune
Ben Fortune

Reputation: 32127

BodyParser doesn't include file uploads. You need to use something like multer or multiparty.

Also express (4.0+) doesn't come bundled with middleware anymore, so you'll need to use bodyparser for POST requests.

Upvotes: 0

Related Questions