Angularjs实现上传图片预览功能
程序员文章站
2022-07-06 20:39:41
废话不多说了,直接给大家贴代码了,具体代码如下所示:
废话不多说了,直接给大家贴代码了,具体代码如下所示:
<input type="file" ng-file-select="onfileselect($files)" accept="image/*"> app.factory("filereader", 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 onprogress = function(reader, scope) { return function (event) { scope.$broadcast("fileprogress", { total: event.total, loaded: event.loaded }); }; }; var getreader = function(deferred, scope) { var reader = new filereader(); reader.onload = onload(reader, deferred, scope); reader.onerror = onerror(reader, deferred, scope); reader.onprogress = onprogress(reader, 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 }; });
选择图片后执行的方法
$scope.onfileselect = function(files) { var filein=files[0]; var img = new image(); var filetype = 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实现上传图片预览功能,希望对大家有所帮助