Angularjs实现图片预览上传
程序员文章站
2022-03-21 23:43:15
...
这次给大家带来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); }); }
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
以上就是Angularjs实现图片预览上传的详细内容,更多请关注其它相关文章!
上一篇: 读大数据量的XML文件的读取问题
推荐阅读