版权声明:本文可转载 ,但转载必须注明出处并附带本文链接 https://blog.csdn.net/qq_27868533/article/details/80271389
封装angularJs上传图片的指令多不胜数,只能上传图片,无法判断图片的宽高,往往对于某些特定的界面,想要最好的客户体验必须上传特定比例或大小的图片。封装一个功能齐全的指令可以剩下很多重复工作。
上传图片
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>title</title>
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body ng-app="myApp">
<input type="file" file-model="myFile">
</body>
<script>
angular.module("myApp", []).directive('fileModel', ["$rootScope", '$parse', '$http', function ($rootScope, $parse, $http) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
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];
var fd = new FormData();
var file = scope.file;
fd.append('file', file);
$http({
method: 'POST',
url: '上传图片接口url',
data: fd,
headers: {'Content-Type': undefined}
})
.success(function (response) {
if (response.success) {
console.log(response)
}
});
});
}
};
}])
</script>
</html>
设定上传图片的宽高
替换上述代码中的上传接口url
就可以实现图片上传。下面就定义两个属性,一个设定图片的宽,另一个设定图片的高:
<input type="file" file-model="myFile" img-width="350" img-height="200">
获取设定值:
var imgWidth = attrs.imgWidth;
var imgHeight = attrs.imgHeight;
已经获得设定值只需在图片上传成功后判断返回图片的大小即可:
$http({
method: 'POST',
url: '上传图片接口url',
data: fd,
headers: {'Content-Type': undefined}
})
.success(function (response) {
if (response.success) {
scope.file.imgUrl = response.imgUrl; // 上传成功将返回的图片路径赋给绑定的变量
var image = new Image();
var width,height;
image.onload = function(){
width = image.width;
height = image.height;
console.log("当前图片宽度为:", width + " 当前图片高度为:"+ height );
if (width == parseInt(imgWidth) && height == parseInt(imgHeight)) {
scope.file.sizeStatus = false; // 可用来显示尺寸错误提示
} else {
scope.file.sizeStatus = true;
}
};
image.src = response.result.pic_url;
}
});
图片大小判断和预览详细请看我的另一篇笔记 上传图片预览及其获取图片宽高
上传的图片调用
之前在判断图片尺寸是否合格时已经定义了绑定变量属性 imgUrl
在调用上传图片时,直接使用 $scope.myFile.imgUrl
即可,当然预览也是同理:
<img ng-src="{{myFile.imgUrl}}">
上传成功后图片就会显示出来。