bogdanbiv / app.js secret
Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

http://stackoverflow.com/questions/21507910/express-500-typeerror-cannot-read-property-image-of-undefined I'm trying to upload an image file using the Express NodeJS framework but it keeps throwing this error: Express 500 TypeError: Cannot read property 'image' of undefined

View app.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
var express = require('express');
var routes = require('./index');
var uploads = require('./uploads');
var http = require('http');
var path = require('path');
 
var app = express();
 
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.bodyParser());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
 
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
 
app.get('/', routes.index);
app.post('/uploads', uploads.uploads);
 
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
View app.js
1 2 3 4
form(enctype="multipart/form-data" action="" method="post")
input(type="file", id = "image", name="image", accept="image/*")
form(method='post' action='uploads')
input(type='submit' id='tags' value='Upload')
View app.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
var fs = require("fs");
 
exports.uploads = function(req, res){
//console.log(req.files);
fs.readFile(req.files.image.path, function (err, data) {
 
console.log("Request handler upload was called");
var imageName = req.files.image.name;
console.log(imageName);
 
if(!imageName){
 
console.log("There was an error")
res.redirect("/");
res.end();
 
} else {
 
var newPath = __dirname + "/uploads/" + imageName;
 
 
fs.writeFile(newPath, data, function (err) {
 
 
res.redirect("/uploads/" + imageName);
 
});
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.