I have the following ajax code that makes a POST request for a blob to the server,and prints the returned data.
function upload(blob){
var formData = new FormData();
formData.append('file', blob);
$.ajax({
url: "http://custom-url/record.php",
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
}
});
}
How can I do the same thing in AngularJS?
Instead of appending the blob to FormData, it is more efficient to send the blob directly as the base64 encoding of the FormData API has an extra 33% overhead.
var config = { headers: { 'Content-Type': undefined } };
$http.post(url, blob, config)
.then(function (response) {
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
console.log("Success", status);
return response;
}).catch(function (errorResponse) {
console.log("Error", errorResponse.status);
throw errorResponse;
});
It as important to set the content type header to undefined
so that the XHR send method can set the content type header. Otherwise the AngularJS framework will override with content type application/json
.
For more information, see AngularJS $http Service API Reference.
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