Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 295
flashpunk Avatar asked Oct 16 '13 19:10

flashpunk


4 Answers

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
}
like image 189
Srisudhir T Avatar answered Nov 11 '22 20:11

Srisudhir T


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.

like image 34
whtlnv Avatar answered Nov 11 '22 21:11

whtlnv


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.

like image 3
rolin.tencent.Shenzhen Avatar answered Nov 11 '22 21:11

rolin.tencent.Shenzhen


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

like image 1
Vishwajeet Avatar answered Nov 11 '22 21:11

Vishwajeet