angularjs 图片上传
Posted 11个条子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了angularjs 图片上传相关的知识,希望对你有一定的参考价值。
<input type="file" file-model="myFile"/>
<div class="col-md-12">
<img ng-src="{{imageSrc}}" style="max-width:68px;max-height:68px;display:block;" />
</div>
//controller
$scope.getFile = function (files) {
console.log(files);
fileReader.readAsDataUrl(files, $scope)
.then(function (result) {
$scope.imageSrc = result;
console.log(result);
});
};
$scope.leaveSubmit = function (e) {
console.log($scope.messages);
if ($scope.messages ===‘‘ || $scope.messages === undefined){
$ionicLoading.show({
template: ‘请填写您的需求!‘,
duration: 2000,
showBackdrop: false
});
return;
}
var data = {
fileName: $scope.imageSrc
// userFeedback: $scope.userFeedback.message
};
var fd = new FormData();
angular.forEach(data, function(val, key) {
fd.append(key, val);
});
$http({
url: "",
data: fd,
headers: {‘Content-Type‘: undefined},
transformRequest: angular.identity
}).success(function (res) {
console.log(‘1‘+ res);
}).error(function (err) {
console.log(err);
$rootScope.showMsg("网络错误");
})
};
app.directive(‘fileModel‘, [‘$parse‘, function ($parse) {
return {
restrict: ‘A‘,
link: function (scope, element, attrs, ngModel) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind(‘change‘, function (event) {
scope.$apply(function () {
modelSetter(scope, element[0].files[0]);
});
//附件预览
scope.file = (event.srcElement || event.target).files[0];
console.log(scope.file);
scope.getFile(scope.file);
});
}
};
}]);
Mine.factory(‘fileReader‘, ["$q", "$log", function ($q, $log) {
var onLoad = function (reader, deferred, scope) {
return function () {
scope.$apply(function () {
deferred.resolve(reader.result);
});
};
};
var onError = function (reader, deferred, scope) {
return function () {
scope.$apply(function () {
deferred.reject(reader.result);
});
};
};
var getReader = function (deferred, scope) {
var reader = new FileReader();
reader.onload = onLoad(reader, deferred, scope);
reader.onerror = onError(reader, deferred, scope);
return reader;
};
var readAsDataURL = function (files, scope) {/*上传图片的主函数*/
console.log(files);
var deferred = $q.defer();
var reader = getReader(deferred, scope);
reader.readAsDataURL(files);
return deferred.promise;
};
return {
readAsDataUrl: readAsDataURL
};
}]);
以上是关于angularjs 图片上传的主要内容,如果未能解决你的问题,请参考以下文章