0

我正在使用 NodeJS、ExpressJS、猫鼬、EJS。

上传表格:

<form method='post' enctype='multipart/form-data'>
    <input type='text' name='photo[name]'/>
    <input type='file' name='photo[image]'/>
    <input type='submit' value='Upload'/>
</form>

模型:

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/photo_app');
var schema = new mongoose.Schema({
    name: String,
    path: String
});

module.exports = mongoose.model('Photo', schema);   

app.js

var app = express();
...
app.set('view engine', 'ejs');
app.use(express.logger('dev'));
app.use(express.bodyParser());
...

路线:

var Photo = require('../models/Photo');
var path = require('path');
var fs = require('fs');
var join = path.join;

exports.submit = function (dir) {
    return function(req, res, next){
        var img = req.files.photo.image;
        var name = req.body.photo.name || img.name;
        var path = join(dir, img.name);
        fs.rename(img.path, path, function(err){
            if (err)
                return next(err);
            Photo.create({
                name: name,
                path: img.name
            }, function (err) {
                if (err)
                    return next(err);
                res.redirect('/');
            });
        });
    };
};

尝试上传时的问题:

500 TypeError: Cannot read property 'photo' of undefined
4

2 回答 2

1

我遇到了同样的问题,我所做的是将几个选项传递给 bodyParser 对象。

app.use(express.bodyParser({ keepExtensions: true, uploadDir: __dirname + '/public/photos' }));

在我添加选项后,一切似乎对我来说都很好。

于 2013-08-15T02:02:31.183 回答
0

使用 connect-multiparty 并将其包含在您的路由文件中:

var multipart=require('connect-multiparty');

然后用作:

app.post('/uploads',multipart(),function(req,res){
    // ...
});
于 2015-10-03T06:57:53.650 回答