1

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
}

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.