我正在尝试使用AngularJS和Node.js(使用Express.js)上传文件。我正在使用danialfarid/angular-file-upload。在我看来(我用玉)我有
label Upload avatar
input(type="file" ng-file-select='uploadAvatar($files)' accept="image/png, image/jpeg")
span(ng-show='uploadInProgress') Upload progress: {{ uploadProgress }}
img(ng-src='uploadedAvatar' ng-if='uploadedAvatar')
这是我的控制器中的uploadAvatar
函数(我在前端使用CoffeeScript,here是已编译的javascript版本):
$scope.uploadAvatar = (image) ->
if angular.isArray image
image = image[0]
if image.type isnt 'image/png' and image.type isnt 'image/jpeg'
alert('Only PNG and JPEG are supported')
return
$scope.uploadInProgress = true
$scope.uploadProgress = 0
$scope.upload = $upload.upload({
url: '/api/users/avatar',
method: 'POST',
file: image
}).progress( (event) ->
$scope.uploadProgress = Math.floor(event.loaded / event.total)
$scope.$apply()
).success( (data, status, headers, config) ->
$scope.uploadInProgress = false
$scope.uploadedAvatar = JSON.parse(data)
).error( (err) ->
$scope.uploadInProgress = false
alert "error"
console.log "error: #{err.message || err}"
)
这是我的路线:
app.post('/api/users/avatar', middleware.auth, users.uploadAvatar);
问题是在我的users.uploadAvatar
控制器中我无法访问该文件:
exports.uploadAvatar = function(req, res, next) {
var currentUser = req.user;
console.log(req.files); // Output is undefined
// Some other code
}
答案 0 :(得分:2)
您忘记使用bodyParser,但现在它不会处理多部分,因此您必须使用multiparty
及其小兄弟connect-multiparty
。使用express 4.x或3.x:
var multipart = require('connect-multiparty');
app.post('/api/users/avatar', middleware.auth, multipart(), users.uploadAvatar);