I am just learning node.js and can hardly make simple file uploads using express and multer .
Here is the form:
Upload image
In my configure.js , I have:
app.use(express.static(path.join(__dirname, 'public'))); app.use(multer({dest:'../public/upload/temp'}).single('file'));
And the image.js controller:
create: function(req, res) { var saveImage = function() { console.log(req.body); var possible = 'abcdefghijklmnopqrstuvwxyz0123456789', imgUrl = ''; for(var i=0; i < 6; i+=1) { imgUrl += possible.charAt(Math.floor(Math.random() * possible.length)); } var tempPath = req.files.file.path,
However, I get this error when trying to upload an image:
TypeError: Cannot read property 'file' of undefined at saveImage (/home/pc/node-dev/test-proj/controllers/image.js:55:37) at module.exports.create (/home/pc/node-dev/test-proj/controllers/image.js:76:9) at Layer.handle [as handle_request] (/home/pc/node-dev/test-proj/node_modules/express/lib/router/layer.js:95:5) at next (/home/pc/node-dev/test-proj/node_modules/express/lib/router/route.js:131:13) at Route.dispatch (/home/pc/node-dev/test-proj/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/home/pc/node-dev/test-proj/node_modules/express/lib/router/layer.js:95:5) at /home/pc/node-dev/test-proj/node_modules/express/lib/router/index.js:277:22 at Function.process_params (/home/pc/node-dev/test-proj/node_modules/express/lib/router/index.js:330:12) at next (/home/pc/node-dev/test-proj/node_modules/express/lib/router/index.js:271:10) at urlencodedParser (/home/pc/node-dev/test-proj/node_modules/body-parser/lib/types/urlencoded.js:95:37)
And when I register the req object, file does not exist:
{ title: 'myimage', description: 'something' }
In fact, the snippet is just a slightly modified version that I read in this book that uses the deprecated express-3. So I just updated it using the multer part.
I wonder what is wrong here and how to fix it.
source share