Aya*_*yan 6 ajax post blob http-post angularjs
我有以下 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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
我如何在 AngularJS 中做同样的事情?
直接发送blob比将 blob 附加到FormData更有效,因为FormData API的base64 编码会产生额外 33% 的开销。
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;
});
Run Code Online (Sandbox Code Playgroud)
设置内容类型标头也很重要,undefined以便XHR 发送方法可以设置内容类型标头。否则 AngularJS 框架将用 content type 覆盖application/json。
有关更多信息,请参阅AngularJS $http 服务 API 参考。
| 归档时间: |
|
| 查看次数: |
5114 次 |
| 最近记录: |