相思资源网 Design By www.200059.com

废话不多说了,直接给大家贴代码了,具体代码如下所示:

<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实现上传图片预览功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

标签:
angularjs,上传图片,angularjs,图片预览

相思资源网 Design By www.200059.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
相思资源网 Design By www.200059.com

评论“Angularjs实现上传图片预览功能”

暂无Angularjs实现上传图片预览功能的评论...