I have an API endpoint to which I must send a multipart HTTP request, composed of two parts, file
(a file system file) and data
(a JSON object).
The easiest way to upload files in Angular:
var fd = new FormData();
fd.append('file', file);
fd.append('data', 'string');
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
Absolutely essential are the following two properties of the config object:
transformRequest: angular.identity
overrides Angular's default serialization, leaving our data intact.
headers: {'Content-Type': undefined }
lets the browser detect the correct Content-Type
as multipart/form-data
, and fill in the correct boundary.
Nothing else worked for me! Courtesy of Lady Louthan's wonderful blogpost.