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

前端之家收集整理的这篇文章主要介绍了如何在AngularJS中为blob发出POST请求前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下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中做同样的事情?

解决方法

由于 FormData APIbase64 encoding具有额外的33%开销,因此直接发送 blob而不是附加 blobFormData更为有效.

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非常重要,以便XHR send method可以设置内容类型标头.否则,AngularJS框架将覆盖内容类型application / json.

有关更多信息,请参阅AngularJS $http Service API Reference.

猜你在找的Angularjs相关文章