我正在学习MEAN堆栈,并试图构建一个简单的文件上传应用程序。然而,我不断击中错误,我可能会走向错误的方向。我最近的错误如下:
<h1>Cannot read property 'file' of undefined</h1>
<h2></h2>
<pre>TypeError: Cannot read property 'file' of undefined
at routesindex.js:34:27
at Layer.handle [as handle_request] (node_modulesexpresslibrouterlayer.js:95:5)
at next (node_modulesexpresslibrouterroute.js:131:13)
at node_modulesexpress-jwtlibindex.js:112:9
at node_modulesjsonwebtokenindex.js:98:18
at process._tickCallback (node.js:355:11)</pre>
这是我的index.ejs
文件:
<form ng-submit="addPhoto()" ng-model="image" enctype="multipart/form-data">
<label for="imageFile">File input</label>
<input type="file" id="imageFile" ng-model="file">
<button type="submit" class="btn btn-primary">Post</button>
</form>
routesindex.js
文件代码:
router.post('/photos', auth, function(req, res, next) {
var dirname = require('path').dirname(__dirname);
var filename = req.files.file.name;
var path = req.files.file.path;
var type = req.files.file.mimetype;
var read_stream = fs.createReadStream(dirname + '/' + path);
var conn = req.conn;
var Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;
var gfs = Grid(conn.db);
var writestream = gfs.createWriteStream({
filename: filename
});
read_stream.pipe(writestream);
photo.save(function(err, photo){
if(err){ return next(err); }
res.json(photo);
});
});
下面是angularApp.js
文件:
app.factory('photos', ['$http', 'auth', function($http, auth){
var o = { photos: [] };
o.create = function(photo) {
return $http.post('/photos', photo, {
headers: {Authorization: 'Bearer '+auth.getToken()}
}).success(function(data){
o.photos.push(data);
}).error(function(a) {
console.log(a);
});
};
return o;
}]);
app.controller('MainCtrl', [
'$scope',
'photos',
'auth',
function($scope, photos, auth){
$scope.photos = photos.photos;
$scope.addPhoto = function(){
photos.create();
};
}]);
虽然这个问题是专门针对我上面展示的错误的,但是一个指向正确方向的指针会很有帮助。
编辑:这是我的app.js
,与Multer代码:
var mongoose = require('mongoose');
var passport = require('passport');
var express = require('express');
var multer = require('multer');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
app.use(multer({'dest': './uploads'}).single('photo'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(passport.initialize());
app.use('/uploads', express.static(__dirname + '/uploads'));
我猜您缺少一个节点模块来接受多部分表单数据。如果你使用默认的带有express的body-parser模块来解析表单数据,那么对于多部分/*表单内容,如文件上传,它将失败。
可以用来解决这个问题的模块之一是Multer。您可以尝试如下:var express = require('express'),
multer = require('multer'),
bodyParser = require('body-parser'),
app = express();
app.use(multer({
'dest': './uploads'
}));
app.use(bodyParser.json());
在Angular.js模板中的<form>
标签中,添加一个属性enctype="multipart/form-data"
。你可以走了
Multer将解析表单中的文件并将其添加到请求中。对象,并以唯一的文件名将其上传到指定的目标目录。这个文件名可以通过request.file. name
访问。一个很好的教程可以在这里找到