如何在AngularJS中为blob发出POST请求 [英] How to make a POST request for a blob in AngularJS

查看:807
本文介绍了如何在AngularJS中为blob发出POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

}

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

How can I do the same thing in AngularJS?

推荐答案

而不是附加 blob FormData ,发送 blob <更高效/ a>直接作为 base64编码 .mozilla.org / zh-CN / docs / Web / API / FormDatarel =nofollow noreferrer> FormData API 额外增加33%。

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

将内容类型标题设置为 undefined 以便 XHR发送方法可以设置内容类型标题。否则,AngularJS框架将覆盖内容类型 application / json

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.

有关更多信息,请参阅 AngularJS $ http服务API参考

For more information, see AngularJS $http Service API Reference.

这篇关于如何在AngularJS中为blob发出POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆