直接发送文件更有效。
该Base64编码的Content-Type: multipart/form-data增加了额外的33%的开销。如果服务器支持它,则直接发送文件更有效:$scope.upload=function(url,file){
varconfig={headers:{'Content-Type':undefined},
transformResponse:angular.identity};
return$http.post(url,file,config);};
使用File对象发送POST时,设置很重要'Content-Type': undefined。然后,XHR send方法将检测File对象并自动设置内容类型。我想我应该从input type =“file”开始,但后来发现AngularJS无法绑定到那个..
默认情况下,该元素不适用于ng-model指令。它需要一个自定义指令:
使用“select-ng-files”指令的工作演示ng-model
angular.module("app",[]);
angular.module("app").directive("selectNgFiles", function() {
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
elem.on("change", function(e) {
var files = elem[0].files;
ngModel.$setViewValue(files);
})
}
}
});
AngularJS Input `type=file` Demo
Files
{{file.name}}
$http.post内容类型multipart/form-data
如果必须发送multipart/form-data:
save
$scope.upload=function(){
varfd=newFormData();
fd.append("data",angular.toJson($scope.fdata));
for(i=0;i
fd.append("file"+i,$scope.filesArray[i]);
};
varconfig={headers:{'Content-Type':undefined},
transformRequest:angular.identity}
return$http.post(url,fd,config);};
使用FormData API发送POST时,设置很重要'Content-Type': undefined。然后,XHR发送方法将检测FormData对象并自动将内容类型标头设置为具有适当边界的multipart / form-data。