一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

AngularJs上传前预览图片的实例代码

时间:2017-02-09 编辑:简简单单 来源:一聚教程网

在工作中,使用AngularJs进行开发,在项目中,经常会遇到上传图片后,需在一旁预览图片内容,之前查了一些资料,结合实践,得出一种比较实用的方法,相对简化版,在这里记录一下,如有不同看法,欢迎一起沟通,一起成长。

demo.html:

 代码如下 复制代码

 

 demo

 

 

 

 

 

  

   

主视觉图:

  

  

 

 

  

 

myCtrl.js:

//关键 js 部分

varmyTestCtrl = angular.module('myTestCtrl', []);

//定义“上传”指令,修改后也可用于上传其他类型的文件

myTestCtrl.directive("imgUpload",function(){

 return{

  //通过设置项来定义

  restrict:'AE',

  scope:false,

  template:'

',//name:testReport 与接口字段相对应。

  replace:true,

  link:function(scope, ele, attrs) {

   ele.bind('click',function() {

    $('#file').val('');

   });

   ele.bind('change',function() {

    scope.file = ele[0].children[1].files;

    if(scope.file[0].size > 52428800){

     alert("图片大小不大于50M");

     scope.file =null;

     returnfalse;

    }

    scope.fileName = scope.file[0].name;

    varpostfix = scope.fileName.substring(scope.fileName.lastIndexOf(".")+1).toLowerCase();

    if(postfix !="jpg"&& postfix !="png"){

     alert("图片仅支持png、jpg类型的文件");

     scope.fileName ="";

     scope.file =null;

     scope.$apply();

     returnfalse;

    }

    scope.$apply();

    scope.reader =newFileReader();//创建一个FileReader接口

    console.log(scope.reader);

    if(scope.file) {

     //获取图片(预览图片)

     scope.reader.readAsDataURL(scope.file[0]);//FileReader的方法,把图片转成base64

     scope.reader.onload =function(ev) {

      scope.$apply(function(){

       scope.thumb = {

        imgSrc : ev.target.result //接收base64,scope.thumb.imgSrc为图片。

       };

      });

     };

    }else{

     alert('上传图片不能为空!');

    }

   });

  }

 };

});

myTestCtrl.controller("myTestCtrl",function($scope, $http) {

 //导入图片

 $scope.saveClick =function() {

  //禁用按钮

  $scope.imgDisabled =true;

  $scope.submitDisabled =true;

  varurl ='';//接口路径

  varfd =newFormData();

  fd.append('testReport', $scope.file[0]);//参数 testReport=后台定义上传字段名称 ; $scope.file[0] 内容

  $http.post(url, fd, {

   transformRequest: angular.identity,

   headers: {

    'Content-Type': undefined

   }

  }).success(function(data) {

   if(data.code != 100) {

    alert(JSON.stringify('文件导入失败:'+files.files[0].name+',请重新上传正确的文件或格式'));

   }else{

    alert(JSON.stringify('文件导入成功:'+files.files[0].name));

   }

   //恢复按钮

   $scope.imgDisabled =false;

   $scope.submitDisabled =false;

  }).error(function(data) {

   alert('服务器错误,文件导入失败!');

   //恢复按钮

   $scope.imgDisabled =false;

   $scope.submitDisabled =false;

  });

 };

});


热门栏目