使用Multer在Express.js中上传文件时出错

时间:2017-11-11 22:10:16

标签: javascript node.js mongodb express multer

我正在从一本书中学习Node.js"使用Nodejs和MongoDB进行Web开发"并且被困在我必须使用Multer上传图像的位置。 守则是这样的: -

以下是我的Configure.js文件:

var path = require('path'),
routes = require('./routes'),
exphbs = require('express-handlebars'),
express = require('express'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
morgan = require('morgan'),
methodOverride = require('method-override'),
errorHandler = require('errorhandler');
multer = require('multer');
moment = require('moment');
var upload = multer({ dest: './public/upload/temp' });
module.exports = function(app) {
app.use(morgan('dev'));
app.use(methodOverride());
app.use(cookieParser('some-secret-value-here'));
routes(app);

app.post('/public/upload/temp', upload.single('img'), function(req, res) {
    //var form_description = req.body.description;
    console.log(req.file.name);
    //  insert operations into database get placed here
    res.redirect('/');
});

app.use('/public/', express.static(path.join(__dirname,
    '../public')));

if ('development' === app.get('env')) {
    app.use(errorHandler());
}

app.engine('handlebars', exphbs.create({
    defaultLayout: 'main',
    layoutsDir: app.get('views') + '/layouts',
    partialsDir: app.get('views') + '/partials',
    helpers: {
        timeago: function(timestamp) {
            return moment(timestamp).startOf('minute').fromNow();
        }
    }
}).engine);
return app;
};

以下是Handlebar文件或(HTML)文件: -

<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">
Upload an Image
</h3>
</div>
<form method="post" action="/images" enctype="multipart/formdata">
<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>
<div class="form-group col-md-12">
<label class="col-md-2 control-label" for="title">Title:</label>
<div class="col-md-10">
<input class="form-control" type="text" name="title">
</div>
</div>
<div class="form-group col-md-12">
<label class="col-md-2 control-label" for="description">Description
</label>
<div class="col-md-10">
<textarea class="form-control" name="description" rows="2"></textarea>
</div>
</div>
<div class="form-group col-md-12">
<div class="col-md-12 text-right">
<button type="submit" id="login-btn"
class="btn btn-success" type="button">
<i class="fa fa-cloud-upload ">
</i> Upload Image</button>
</div>
</div>
</div>
</form>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
</h3>
</div>
<div class="panel-body">
{{#each images}}
<div class="col-md-4 text-center" style="padding-bottom:1em;">
<a href="/images/{{ uniqueId }}">
<img src="/public/upload/{{filename}}" alt="{{title}}" style="width:
175px; height: 175px;" class="imgthumbnail">
</a></div>
{{/each}}
</div>
</div>

下面是image.js控制器文件: -

var fs = require('fs');
var path = require('path');
module.exports = {
index: function(req, res) {
    var viewModel = {
        image: {
            uniqueId: 1,
            title: 'Sample Image 1',
            description: 'This is a sample.',
            filename: 'sample1.jpg',
            views: 0,
            likes: 0,
            timestamp: Date.now
        },
        comments: [{
            image_id: 1,
            email: 'test@testing.com',
            name: 'Test Tester',
            gravatar: 'http://lorempixel.com/75/75/animals/1',
            comment: 'This is a test comment...',
            timestamp: Date.now
        }, {
            image_id: 1,
            email: 'test@testing.com',
            name: 'Test Tester',
            gravatar: 'http://lorempixel.com/75/75/animals/2',
            comment: 'Another followup comment!',
            timestamp: Date.now
        }]
    };
    res.render('image.handlebars', viewModel);
},
create: function(req, res) {
    var possible = 'abcdefghijklmnopqrstuvwxyz0123456789',
        imgUrl = '';
    for (var i = 0; i < 6; i += 1) {
        imgUrl += possible.charAt(Math.floor(Math.random() *
            possible.length));
    }
    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.' });
        });
    }
},
like: function(req, res) {
    res.send('The image:like POST controller');
},
comment: function(req, res) {
    res.send('The image:comment POST controller');
}
};

运行服务器并访问localhost上的网站并尝试通过单击“上载图像”按钮上传图像时出现此错误: -

无法读取属性&#39;路径&#39;未定义的

at create (G:\Docs\Node.js\Project\imgploader.io\controllers\image.js:40:32)
at Layer.handle [as handle_request] (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\layer.js:95:5)
at next (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\layer.js:95:5)
at G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\index.js:281:22
at Function.process_params (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\index.js:335:12)
at next (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\index.js:275:10)
at Function.handle (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\index.js:174:3)
at router (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\index.js:47:12)

问题是什么?我已尝试在互联网上提供的所有内容但仍然相同! 请帮忙

1 个答案:

答案 0 :(得分:0)

也许是因为你在错误处理程序声明结束时使用了(;)

errorHandler = require('errorhandler');

同样在您的HTML名称属性中应该是img,因为您已经使用了multer。