这次给大家带来Angularjs实现图片预览上传,Angularjs实现图片预览上传的注意事项有哪些,下面就是实战案例,一起来看一下。
废话不多说了,直接给大家贴代码了,具体代码如下所示:
<input type="file"ng-file-select="onFileSelect($files)"accept="image/*"> app.factory("fileReader",function($q, $log) { varonLoad =function(reader, deferred, scope) { returnfunction() { scope.$apply(function() { deferred.resolve(reader.result); }); }; }; varonError =function(reader, deferred, scope) { returnfunction() { scope.$apply(function() { deferred.reject(reader.result); }); }; }; varonProgress =function(reader, scope) { returnfunction(event) { scope.$broadcast("fileProgress", { total: event.total, loaded: event.loaded }); }; }; vargetReader =function(deferred, scope) { varreader =newFileReader(); reader.onload = onLoad(reader, deferred, scope); reader.onerror = onError(reader, deferred, scope); reader.onprogress = onProgress(reader, scope); returnreader; }; varreadAsDataURL =function(file, scope) { vardeferred = $q.defer(); varreader = getReader(deferred, scope); reader.readAsDataURL(file); returndeferred.promise; }; return{ readAsDataUrl: readAsDataURL }; });
选择图片后执行的方法
$scope.onFileSelect =function(files) { varfileIn=files[0]; varimg =newImage(); varfileType = fileIn.name.substring(fileIn.name.lastIndexOf(".") + 1, fileIn.name.length); if(fileIn.size>5242880){//单位是B,此处不允许超过5M alert("图片不能超过5M") return; } if(fileType=='JPG'|| fileType=='PNG'|| fileType=='JPEG '|| fileType=='jpg'|| fileType=='png'|| fileType=='jpeg'){ }else{ alert("图片格式只支持:JPG,PNG,JPEG") return; } fileReader.readAsDataUrl(fileIn, $scope) .then(function(result) { $scope.imageSrc = result; console.log(img.width); }); }
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
Atas ialah kandungan terperinci Angularjs实现图片预览上传. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!