Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a POST request for a blob in AngularJS

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?

like image 498
Ayan Avatar asked Mar 04 '17 14:03

Ayan


1 Answers

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.

like image 134
georgeawg Avatar answered Oct 21 '22 21:10

georgeawg