How to POST FormData Using the $http Service
When using the FormData API to POST files and data, it is important to set the Content-Type header to undefined
.
var fd = new FormData()
for (var i in $scope.files) {
fd.append("fileToUpload", $scope.files[i]);
}
var config = {headers: {'Content-Type': undefined}};
var httpPromise = $http.post(url, fd, config);
By default the AngularJS framework uses content type application/json
. By setting Content-Type: undefined
, the AngularJS framework omits the content type header allowing the XHR API to set the content type. When sending a FormData object, the XHR API sets the content type to multipart/form-data
with the proper boundaries and base64 encoding.
For more information, see MDN Web API Reference - XHR Send method
what's the difference between using $http
and XMLHttpRequest
? which one is better and why?
The $http Service is the AngularJS wrapper for the XMLHttpRequest (XHR) API. It converts the callback based asynchronous API to a $q service promise based API. It is integrated with the AngularJS framework and its digest cycle.
If the app is using the AngularJS framework to render the model, it should be using the AngularJS framework to communicate with the server.
Angular frees you from the following pains:
Registering callbacks: Registering callbacks clutters your code, making it hard to see the forest for the trees. Removing common boilerplate code such as callbacks is a good thing. It vastly reduces the amount of JavaScript coding you have to do, and it makes it easier to see what your application does.
Manipulating HTML DOM programmatically
- Marshaling data to and from the UI
- Writing tons of initialization code just to get started
For more information, see: