我正在学习MEAN堆栈并且正在尝试构建一个简单的文件上传应用程序。但是,我不断遇到错误,我可能正朝着错误的方向前进。我的最新错误如下:
<h1>Cannot read property 'file' of undefined</h1>
<h2></h2>
<pre>TypeError: Cannot read property 'file' of undefined
at \routes\index.js:34:27
at Layer.handle [as handle_request] (\node_modules\express\lib\router\layer.js:95:5)
at next (\node_modules\express\lib\router\route.js:131:13)
at \node_modules\express-jwt\lib\index.js:112:9
at \node_modules\jsonwebtoken\index.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>
routes\index.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'));
答案 0 :(得分:0)
我猜你错过了一个接受多部分表单数据的节点模块。如果您使用带有express的默认正文解析器模块来解析表单数据,那么对于多部分/ *表单内容(例如文件上载)将会失败。
您可以用来解决此问题的模块之一是Multer。你可以尝试如下:
var express = require('express'),
multer = require('multer'),
bodyParser = require('body-parser'),
app = express();
app.use(multer({
'dest': './uploads'
}));
app.use(bodyParser.json());
&#13;
在Angular.js模板中的<form>
标记中,添加属性enctype="multipart/form-data"
。你很高兴。
Multer将解析您的表单以获取文件并将其添加到request.files对象,并将其上传到具有唯一文件名的指定目标目录。此文件名可以从request.file..name
可以找到一个好的教程here