如果文件扩展区的大小是我的代码,我想从服务将数据发送回我的控制器。
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function (fileData, uploadUrl) {
if (fileData.size > 50000000) {
var fd = new FormData();
fd.append('file', fileData);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
})
.success(function () {
})
.error(function () {
});
}
else {
return "Image size is more than 5MB";
}
}
}]);
您应该使用$ q服务来推迟执行请求,例如-
myApp.service('fileUpload', ['$http','$q', function ($http,$q) {
this.uploadFileToUrl = function (fileData, uploadUrl) {
if (fileData.size > 50000000) {
var fd = new FormData();
fd.append('file', fileData);
var deferred = $q.defer();
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
})
.then(function (result) {
deffered.resolve(result);
},function(error) {
deffered.reject();
});
return deferred.promise;
}
else {
return "Image size is more than 5MB";
}
}
}]);
有关更多信息,请检查以下链接-
https://docs.angularjs.org/api/ng/service/ $ q https://thinkster.io/a-better-way-to-learn-angularjs/promises