angularJS系列:图片预览、压缩及上传功能
[ 2017/05/18, AngularJS , 6716阅, 0评 ]

angularJS图片上传及预览.jpg

壹、html结构

<input type="text" ng-model="orderForm.name">
<input type="file" style="display:none" custom-on-change="chooseOrderImage" name="orderImage" accept="image/jpg,image/jpeg,image/png,image/gif"/>
<div ng-click="doClickMyInput()">
    <img ng-if="!haveChange" ng-src="images/info-card-upload.jpg">
    <img ng-if="haveChange" ng-src="{{imageView}}">
</div>
<textarea ng-model="orderForm.message"></textarea>
<input type="button" ng-click="doSubmitOrder()" value="确认">

贰、定义控制器

myApp.controller("myController",function($scope,$http,fileReader){
	//...
	$scope.orderForm = {
		name: '',
		message: '',
		image: ''
	};
	$scope.haveChange = false;
	$scope.fileName = "";
	$scope.doClickMyInput = function(){
		angular.element("input[name=orderImage]").click();
	};
	$scope.chooseOrderImage = function(event){
		$scope.$apply(function(){
			//得到文件
			$scope.orderForm.image = (event.srcElement || event.target).files[0];
			//得到文件名
			$scope.fileName = $scope.orderForm.image.name;
		});
		$scope.haveChange = true;
		//生成预览图
		fileReader.readAsDataUrl($scope.orderForm.image, $scope).then(function(result){
			$scope.imageView = result;
		});
	};
	$scope.doSubmitOrder = function(){
		if( $scope.orderForm.name == "" ){
			layertip("请填写姓名");
		}else if( ($scope.orderForm.name.length < 2) || ($scope.orderForm.name.length > 10) ){
			layertip("姓名2-10字");
		}else if( ! $scope.orderForm.image ){
			layertip("请上传图片");
		}else if( $scope.orderForm.message.length > 255 ){
			layertip("备注不超过255字");
		}else{
			layer.open({
				content: '确定提交吗?',
				shadeClose: false,
				btn: ['确定', '取消'],
				yes: function(index){
					layer.close(index);
					$http({
						method:"POST",
						url: "yourapi.php",
						headers: {'Content-Type': undefined},
						data: $scope.orderForm,
						transformRequest: function(data,headersGetter) {
							var formData = new FormData();
							angular.forEach(data,function(value,key){
								formData.append(key,value);
							});
							var headers = headersGetter();
							delete headers['Content-Type'];
							return formData;
						},
					}).success(function(res){
						//...
					});
				}
			});
		}
	};
});

叁、定义directive

myApp.directive('customOnChange',function(){
	return {
		restrict:'A',
		link:function(scope,element,attrs){
			var onChangeHandler = scope.$eval(attrs.customOnChange);
			element.bind('change',onChangeHandler);
		}
	};
});

肆、定义factory实现base64编码图片预览

myApp.factory('fileReader', ["$q", "$log", function($q, $log){
	var onLoad = function(reader, deferred, scope) {
		return function () {
			scope.$apply(function () {
				deferred.resolve(reader.result);
			});
		};
		//将缩略图进行压缩
		/*return function (e) {
			scope.$apply(function () {
				var img = document.createElement("img");
				img.src = e.target.result;
				var canvas = document.createElement("canvas");
				var ctx = canvas.getContext("2d");
				ctx.drawImage(img, 0, 0);
				var MAX_WIDTH = 600;
				var MAX_HEIGHT = 384;
				img.onload = function(){
					var width = img.width;
					var height = img.height;
					if (width > height) {
						if (width > MAX_WIDTH) {
							height *= MAX_WIDTH / width;
							width = MAX_WIDTH;
						}
					} else {
						if (height > MAX_HEIGHT) {
							width *= MAX_HEIGHT / height;
							height = MAX_HEIGHT;
						}
					}
					canvas.width = width;
					canvas.height = height;
					var ctx = canvas.getContext("2d");
					ctx.drawImage(img, 0, 0, width, height);
					var dataURL = canvas.toDataURL('image/jpeg',0.2);
					deferred.resolve(dataURL);
				};
			});
		};*/
	};
	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 (file, scope) {
		var deferred = $q.defer();
		var reader = getReader(deferred, scope);         
		reader.readAsDataURL(file);
		return deferred.promise;
	};
	return {
		readAsDataUrl: readAsDataURL  
	};
}])

伍、参考资料

1.Angular中通过ajax上传文件解决方案

2.AngularJS图片上传功能的实现

3.angularJs 取<input type='file'>中文件名


陆、备用代码:图片本地压缩

利用html5的canvas来进行图片的压缩,然后转化为dataURL,再由dataURL转化为Blob文件,Blob对象就可以直接赋值给Formdata了。

controller部分:

$scope.chooseFile = function(event){
	var myfile = (event.srcElement || event.target).files[0];
	imageCompress.resizeFile(myfile).then(function(blob_data) {
		//将结果blob_data上传
	},function(err_reason){
		console.log(err_reason);
	});
};

service部分:

/*图片压缩服务*/
myApp.service('imageCompress', ['$q', function($q){
	var dataURItoBlob = function(dataURI) {
		// convert base64/URLEncoded data component to raw binary data held in a string
		var byteString;
		if(dataURI.split(',')[0].indexOf('base64') >= 0){
			byteString = atob(dataURI.split(',')[1]);
		}else{
			byteString = unescape(dataURI.split(',')[1]);
		}
		// separate out the mime component
		var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
		// write the bytes of the string to a typed array
		var ia = new Uint8Array(byteString.length);
		for (var i = 0; i < byteString.length; i++) {
			ia[i] = byteString.charCodeAt(i);
		}
		return new Blob([ia], {type: mimeString});
	};
	var resizeFile = function(file) {
		var deferred = $q.defer();
		try{
			var reader = new FileReader();
			reader.onload = function(e) {
				var img = document.createElement("img");
				img.src = e.target.result;
				//resize the image using canvas
				var canvas = document.createElement("canvas");
				var ctx = canvas.getContext("2d");
				ctx.drawImage(img, 0, 0);
				var MAX_WIDTH = 750;
				var MAX_HEIGHT = 750;
				img.onload = function(){
					var width = img.width;
					var height = img.height;
					if (width > height) {
						if (width > MAX_WIDTH) {
							height *= MAX_WIDTH / width;
							width = MAX_WIDTH;
						}
					} else {
						if (height > MAX_HEIGHT) {
							width *= MAX_HEIGHT / height;
							height = MAX_HEIGHT;
						}
					}
					canvas.width = width;
					canvas.height = height;
					var ctx = canvas.getContext("2d");
					ctx.drawImage(img, 0, 0, width, height);
					var dataURL = canvas.toDataURL('image/jpeg');
					var blob = dataURItoBlob(dataURL);
					deferred.resolve(blob);
				};
			};
			reader.readAsDataURL(file);
		}catch(e){
			deferred.resolve(e);
		}
		return deferred.promise;
	};
	return {
		resizeFile: resizeFile
	};
}]);

有朋自远方来...评论一下呗O(∩_∩)O