如何在AngularJS中为blob发出POST请求

时间:2017-03-04 14:25:55

标签: angularjs ajax post http-post blob

我有以下ajax代码向服务器发出blob的POST请求,并打印返回的数据。

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);
    }
  });

}

如何在AngularJS中做同样的事情?

1 个答案:

答案 0 :(得分:0)

不是将blob附加到FormData,而是直接发送blob,因为base64 encodingFormData API有额外的33 XHR send method %开销。

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;
});

将内容类型标头设置为undefined非常重要,以便AngularJS $http Service API Reference可以设置内容类型标头。否则,AngularJS框架将覆盖内容类型application/json

有关详细信息,请参阅executable