如何使用$ http服务发布FormData
当使用FORMDATA API以POST文件和数据,它设定的是很重要的Content-Type头到
undefined。
var fd = new FormData()for (var i in $scope.files) { fd.append("fileToUpload", $scope.files[i]);}var config = {headers: {'Content-Type': undefined}};var httpPromise = $http.post(url, fd, config);默认情况下,AngularJS框架使用内容类型
application/json。通过设置
Content-Type:undefined,AngularJS框架省略了内容类型标头,从而允许XHRAPI设置内容类型。发送FormData对象时,XHR API将内容类型设置为
multipart/form-data具有适当的边界和base64编码。
您是如何获取文件信息的
$scope.files?
如何启用<input type="file">
与之合作ng-model
该指令还可以
<input type="file">自动使用
ng-changeand
ng-form指令。
angular.module("app",[]);angular.module("app").directive("selectFilesNg", function() { return { require: "ngModel", link: function postlink(scope,elem,attrs,ngModel) { elem.on("change", function(e) { var files = elem[0].files; ngModel.$setViewValue(files); }) } }});<script src="//unpkg.com/angular/angular.js"></script> <body ng-app="app"> <h1>AngularJS Input `type=file` Demo</h1> <input type="file" select-files-ng ng-model="fileArray" multiple> <pre><table ng-show="fileArray.length"> <tr><td>Name</td><td>Date</td><td>Size</td><td>Type</td><tr> <tr ng-repeat="file in fileArray"> <td>{{file.name}}</td> <td>{{file.lastModified | date : 'MMMdd,yyyy'}}</td> <td>{{file.size}}</td> <td>{{file.type}}</td> </tr> </table></pre> </body>推荐:直接发布二进制文件
使用base64编码添加二进制文件
multi-part/form-data效率很低,因为base64编码会增加33%的额外开销。如果服务器API接受带有二进制数据的POST,请直接发布文件。



