I am using this program example to upload a image into uploads/fullsize directory. The application is running but if I try to upload a image I am getting the following failure:
TypeError: Cannot read property 'image' of undefined at Object.handle (/Users/machupicchu/Desktop/test/app.js:46:23) at next_layer (/Users/machupicchu/Desktop/test/node_modules/express/lib/router/route.js:103:13) at Route.dispatch (/Users/machupicchu/Desktop/test/node_modules/express/lib/router/route.js:107:5) at c (/Users/machupicchu/Desktop/test/node_modules/express/lib/router/index.js:195:24) at Function.proto.process_params (/Users/machupicchu/Desktop/test/node_modules/express/lib/router/index.js:251:12) at next (/Users/machupicchu/Desktop/test/node_modules/express/lib/router/index.js:189:19) at next (/Users/machupicchu/Desktop/test/node_modules/express/lib/router/index.js:166:38) at next (/Users/machupicchu/Desktop/test/node_modules/express/lib/router/index.js:166:38) at Layer.staticMiddleware [as handle] (/Users/machupicchu/Desktop/test/node_modules/express/node_modules/serve-static/index.js:55:61) at trim_prefix (/Users/machupicchu/Desktop/test/node_modules/express/lib/router/index.js:226:17)
The application looks like this:
var express = require('express');
var bodyParser = require('body-parser');
var path = require ('path');
var port = 3000;
var fs = require('fs');
//var collection;
//dataExt = require('./routes/serverExtend');
// setup middleware
var app = express();
app.use(bodyParser());
app.use(express.static(__dirname + '/public')); //setup static public directory
app.set('views', __dirname + '/views'); //optional since express defaults to CWD/views
app.set('view engine', 'ejs');
// Start server
app.listen(port);
console.log('App started on port ' + port);
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);
});
app.get('/uploads/fullsize/:file', function (req, res){
file = req.params.file;
var img = fs.readFileSync(__dirname + "/uploads/fullsize/" + file);
res.writeHead(200, {'Content-Type': 'image/jpg' });
res.end(img, 'binary');
});
/// Post files
app.post('/upload', function(req, res) {
fs.readFile(req.files.image.path, function (err, data) {
var imageName = req.files.image.name
/// If there's an error
if(!imageName){
console.log("There was an error")
res.redirect("/");
res.end();
} else {
var newPath = __dirname + "/uploads/fullsize/" + imageName;
/// write file to uploads/fullsize folder
fs.writeFile(newPath, data, function (err) {
/// let's see it
res.redirect("/uploads/fullsize/" + imageName);
});
}
});
});
Can someone help me why I am getting the TypeError?? Also created my directory where the files should be save. app.js uploads -> fullsize -> images.jpg