I've looked at a lot of answer for this same question, but I haven't found a working solution yet. I am trying to make a web app that you can upload files to using express and multer, and I am having a problem that no files are being uploaded and req.file is always undefined.
Express and multer version as:
"express": "^4.15.4",
"multer": "^1.3.0"
My configure.js looks this:
multer = require('multer');
module.exports = function(app) {
app.use(morgan('dev'));
app.use(multer({
dest: path.join(__dirname, 'public/upload/temp')}).single('file'));
routes(app);
app.use('/public/', express.static(path.join(__dirname, '../public')));
Consuming code looks like this:
var tempPath = req.file.path,
ext = path.extname(req.file.name).toLowerCase(),
targetPath = path.resolve('./public/upload/' + imgUrl + ext);
if (ext === '.png' || ext === '.jpg' || ext === '.jpeg' || ext === '.gif') {
fs.rename(tempPath, targetPath, function(err) {
if (err) throw err;
res.redirect('/images/' + imgUrl);
});
} else {
fs.unlink(tempPath, function() {
if (err) throw err;
res.json(500, {error: 'Only image files are allowed.'});
});
}
The form looks like this:
<form method="post" action="/images" enctype="multipart/form-
data">
<div class="panel-body form-horizontal">
<div class="form-group col-md-12">
<label class="col-sm-2 control-label"
for="file">Browse:</label>
<div class="col-md-10">
<input class="form-control" type="file"
name="file" id="file">
</div>
</div>