I have the below request in python
import requests, json, io
cookie = {}
payload = {"Name":"abc"}
url = "/test"
file = "out/test.json"
fi = {'file': ('file', open(file) )}
r = requests.post("http://192.168.1.1:8080" + url, data=payload, files=fi, cookies=cookie)
print(r.text)
which send a file, and form fields to the backend. How can I do the same (sending file + form fields) with Angular $http. Currently, I do like this, but not sure how to send the file too.
var payload = {"Name":"abc"};
$http.post('/test', payload)
.success(function (res) {
//success
});
$http is an AngularJS service for reading data from remote servers.
I had similar problem when had to upload file and send user token info at the same time. transformRequest
along with forming FormData
helped:
$http({
method: 'POST',
url: '/upload-file',
headers: {
'Content-Type': 'multipart/form-data'
},
data: {
email: Utils.getUserInfo().email,
token: Utils.getUserInfo().token,
upload: $scope.file
},
transformRequest: function (data, headersGetter) {
var formData = new FormData();
angular.forEach(data, function (value, key) {
formData.append(key, value);
});
var headers = headersGetter();
delete headers['Content-Type'];
return formData;
}
})
.success(function (data) {
})
.error(function (data, status) {
});
For getting file $scope.file
I used custom directive:
app.directive('file', function () {
return {
scope: {
file: '='
},
link: function (scope, el, attrs) {
el.bind('change', function (event) {
var file = event.target.files[0];
scope.file = file ? file : undefined;
scope.$apply();
});
}
};
});
Html:
<input type="file" file="file" required />
I was unable to get Pavel's answer working as in when posting to a Web.Api application.
The issue appears to be with the deleting of the headers.
headersGetter();
delete headers['Content-Type'];
In order to ensure the browsers was allowed to default the Content-Type along with the boundary parameter, I needed to set the Content-Type to undefined. Using Pavel's example the boundary was never being set resulting in a 400 HTTP exception.
The key was to remove the code deleting the headers shown above and to set the headers content type to null manually. Thus allowing the browser to set the properties.
headers: {'Content-Type': undefined}
Here is a full example.
$scope.Submit = form => {
$http({
method: 'POST',
url: 'api/FileTest',
headers: {'Content-Type': undefined},
data: {
FullName: $scope.FullName,
Email: $scope.Email,
File1: $scope.file
},
transformRequest: function (data, headersGetter) {
var formData = new FormData();
angular.forEach(data, function (value, key) {
formData.append(key, value);
});
return formData;
}
})
.success(function (data) {
})
.error(function (data, status) {
});
return false;
}
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