0

I have this code for image uploading:

$scope.uploadAvatar = function(e) {
    $scope.uploadAvatarError = false;
    $scope.uploadAvatarSuccess = false;
    var f = document.getElementById('uploadAvatar').files[0],
        fd = new FormData();
    if (!f) {
        return
    }

    fd.append('user', $scope.user.user_email);
    fd.append('photo', f);

    $http.post(apiUrl + 'addProfilePicture', fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    }).then(function(response){
        console.log(response);
    })
}

When I send it to server, it returns status 200, but nothing is uploaded. In network tab in chrome dev tools it says ContentType application/json instead of multipart/form-data. How can I change that?

Marko Mikulić
  • 1,047
  • 2
  • 10
  • 15
  • Most browsers are only able to upload files if `multipart/form-data` is used. I would suggest you to read this answer, maybe it can help a bit: http://stackoverflow.com/a/4073451/1867076 – Prometheus Dec 06 '16 at 13:40
  • Possible duplicate of [how to upload file using Angularjs, multipart/form-data](http://stackoverflow.com/questions/40868451/how-to-upload-file-using-angularjs-multipart-form-data) – georgeawg Dec 06 '16 at 20:39
  • The only difference from your code and [this DEMO on PLNKR](https://plnkr.co/edit/S642uACPAaVFMrGYmRwD?p=preview) is that the demo waits for the "change" event on the file picker element before doing `fd.append`; – georgeawg Dec 06 '16 at 20:46

1 Answers1

0

You can use the very thorough angular-file-upload module to achieve that. If I may, you can even add the preview with this module, which can be useful / nice in case of avatars.

Romain
  • 3,586
  • 7
  • 31
  • 52