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.
You can use this plugin, it's highly configurable too: https://github.com/danialfarid/ng-file-upload
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With