How to make a POST request for a blob in AngularJS

坚强是说给别人听的谎言 提交于 2019-12-10 16:29:26

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/42597106/how-to-make-a-post-request-for-a-blob-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!