0

I am complete Newbie to Node.js.I just want to learn upload and showing images using ajax like i do in php.I found most of the tutorials tough for me.To get started I have tried using this code

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


//all environment
app.use(bodyParser())



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

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

});
/// Post files
app.post('/upload', function(req, res) {
    console.log('Hello world');
       console.log(req.files);
});


app.listen(8080)

But am getting UNDEFINED for req.files.can anybody tell why?.Please forgive me if its a stupid question.And also help with some resources.Thank you in Advance.

1
  • Please take your initial statement out of the code block. Commented May 31, 2014 at 16:00

2 Answers 2

1

req.files is for express v3, you are using v4.

Now body-parser only handles urlencoded and json bodies. For multipart bodies you should use an alternative.

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

For example with multer:

var express = require('express')
var multer  = require('multer')

var app = express()
app.use(multer({ dest: './uploads/'}))

/// Post files
app.post('/upload', function(req, res) {
    console.log('Hello world');
    console.log(req.files);
});

app.listen(8080)
Sign up to request clarification or add additional context in comments.

Comments

1

With express 4, busboy is an excellent way to handle uploaded images. Let's look at a cut-down example from Miaou:

exports.appPostUpload = function(req, res){
    var busboy = new Busboy({ headers: req.headers }), files=[];
    busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
        var chunks = [];
        file.on('data', function(chunk) {
            chunks.push(chunk);             
            // todo : abort if sum of chunk.lengths is too big (and tell the client he's fat)
        });
        file.on('end', function() {
            files.push({name:fieldname, bytes:Buffer.concat(chunks)});
        });
    }).on('finish', function() {
        if (!files.length) {
            return res.send({error:'found nothing in form'});
        }
        // we can now work with the items in `files` like you normally would.
    });
    req.pipe(busboy);       
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.