I'm trying to upload files using AngularJS and Node.js (with Express.js). I'm using danialfarid/angular-file-upload. In my view (I use jade) I have
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')
Here's the uploadAvatar
function in my controller (I use CoffeeScript in the frontend, here is the compiled javascript version):
$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}"
)
Here is my route:
app.post('/api/users/avatar', middleware.auth, users.uploadAvatar);
And the problem is that in my users.uploadAvatar
controller I cannot access the file:
exports.uploadAvatar = function(req, res, next) {
var currentUser = req.user;
console.log(req.files); // Output is undefined
// Some other code
}
You forgot to use bodyParser, but now it doesn't handle multipart, so you have to use multiparty
and its little brother connect-multiparty
. With express 4.x or 3.x:
var multipart = require('connect-multiparty');
app.post('/api/users/avatar', middleware.auth, multipart(), users.uploadAvatar);