首先
- 您无需对结构进行任何特殊更改。我的意思是:html输入标签。
<input accept="image/*" name="file" ng-value="fileToUpload"value="{{fileToUpload}}" file-model="fileToUpload"set-file-data="fileToUpload = value;" type="file" id="my_file" />
1.2创建自己的指令,
.directive("fileModel",function() { return { restrict: 'EA', scope: { setFiledata: "&" }, link: function(scope, ele, attrs) { ele.on('change', function() { scope.$apply(function() { var val = ele[0].files[0]; scope.setFileData({ value: val }); }); }); } } })
- 在带有$ httpProvider的模块中,添加具有multipart / form-data的依赖项(如Accept,Content-Type等)。(建议是接受json格式的响应)例如:
$ httpProvider.defaults.headers.post [‘Accept’] =’application / json,text /
javascript’; $ httpProvider.defaults.headers.post [‘Content-Type’]
=’multipart / form-data; charset = utf-8’;
然后在控制器中创建单独的函数来处理表单提交调用。例如下面的代码:
在服务函数中,要有目的地处理“ responseType”参数,以便服务器不应抛出“ byteerror”。
transformRequest,用于修改带有附加身份的请求格式。
withCredentials:false,用于HTTP认证信息。
in controller: // pre this accordingly, so that your file object // will be picked up in service call below. fileUpload.uploadFileToUrl(file); in service: .service('fileUpload', ['$http', 'ajaxService', function($http, ajaxService) { this.uploadFileToUrl = function(data) { var data = {}; //file object var fd = new FormData(); fd.append('file', data.file); $http.post("endpoint server path to whom sending file", fd, { withCredentials: false, headers: { 'Content-Type': undefined }, transformRequest: angular.identity, params: { fd }, responseType: "arraybuffer" }) .then(function(response) { var data = response.data; var status = response.status; console.log(data); if (status == 200 || status == 202) //do whatever in success else // handle error in else if needed }) .catch(function(error) { console.log(error.status); // handle else calls }); } } }]) <script src="//unpkg.com/angular/angular.js"></script>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)