flashpunk
flashpunk

Reputation: 772

AngularJs Ajax POST form with file upload

I'm trying to set up a form to be submitted using an ajax request to an api that has already been built using Ajax. For some reason the file just doesn't want to transfer to the system although there is already a back end built to handle this, and it works fine.

My service looks like this based on a tutorial I found here: http://badwing.com/multipart-form-data-ajax-uploads-with-angularjs/

addActivity: function(url){
    return $http({
        method: 'POST',
        url: REQUEST_URL + 'Volunteering/AddActivity?token=' + token + url,
        headers: {
            'Content-Type': 'multipart/form-data'
        },
        data: {
            file: $scope.file
        },
        transformRequest: formDataObject
    }).
    then(function(result) {
        console.log(result);
        return result.data;
    });
},

I have a feeling it's just something really minor that i'm missing, can anyone offer some help?

Upvotes: 16

Views: 31606

Answers (4)

Srisudhir T
Srisudhir T

Reputation: 715

I faced a similar problem.

The solution is to use formData

var formData = new FormData();
formData.append("file", $scope.file);

and replace

data: {
    file: $scope.file
}

with

data: {
    formdata
}

Upvotes: 14

Vishwajeet
Vishwajeet

Reputation: 321

You can use this plugin, it's highly configurable too: https://github.com/danialfarid/ng-file-upload

Upvotes: 1

whtlnv
whtlnv

Reputation: 2207

I was having trouble implementing file upload with angular + laravel. Every time I tried sending the multipart form, the server wouldn't receive the form data, even tho it was clearly being sent, or so I thought. I finally found THIS article that solved all my problems.

Long story short, this is the $http call:

var data = new FormData();

data.append("file", file);

$http.post("//myDomain.com/api/demo", data, {
    headers: { 'Content-Type': undefined },
    transformRequest: angular.identity
}).success(function (data, status, headers, config) {

}).error(function (data, status, headers, config) {

});

The other answer by rolin.tencent.Shenzhen also mentioned setting Content-Type as undefined to let the browser sort it out.

Upvotes: 8

rolin.tencent.Shenzhen
rolin.tencent.Shenzhen

Reputation: 174

The data should be data: $scope.file

and important thing : you should set 'Content-Type': undefined to make the browser set the right content type.

Upvotes: 3

Related Questions