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.
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)
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.