简体   繁体   中英

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?

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
}

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.

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.

您可以使用此插件,它也是高度可配置的: https//github.com/danialfarid/ng-file-upload

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM