我是angular.js的初学者,但是我对基础知识有很好的了解。
我要做的是上传文件和一些表单数据作为多部分表单数据。我读到这不是angular的功能,但是3rd party库可以做到这一点。我已经通过git克隆了angular-file-upload,但是仍然无法发布简单的表单和文件。
有人可以提供如何执行此操作的示例,html和js吗?
首先
<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.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:
// code 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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句