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


Posted in Javascript onJanuary 20, 2017

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

demo.html:

<!doctype html> 
<html ng-app="myTestCtrl"> 
<head> 
 <meta charset="UTF-8"> 
 <title>demo</title> 
 <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script> 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
 <script src="myCtrl.js"></script> 
 <style type="text/css"> 
 .inputBox{width: 160px; height: 28px; padding: 0 0 0 8px; box-sizing: border-box; background-color:#fff; margin-left: 5px; border: 1px solid #c4c4c4; color: #333; border-radius: 3px; -o-border-radius: 3px;-moz-border-radius: 3px;-webkit-border-radius: 3px;} 
 .inputBox:focus{border: 1px solid #207fe9;} 
 .btn-primary {color: #fff; background-color: #428bca; border-color: #357ebd;} 
 .btn {display: inline-block; padding: 6px 12px; margin-bottom: 0; font-size: 14px; font-weight: 400;line-height: 1.42857143; text-align: center; white-space: nowrap; vertical-align: middle; -ms-touch-action: manipulation; touch-action: manipulation; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background-image: none; border: 1px solid transparent; border-radius: 4px;} 
 .bg-bbbbbb{background-color: #bbb;} 
 .fl{float:left;} 
 .ml5{margin-left: 5px;} 
 .ml10{margin-left: 10px;} 
 .ml30{margin-left: 30px;} 
 .mt10{margin-top: 10px;} 
 .mt20{margin-top: 20px;} 
 .f-cb:after:after{display:block;clear:both;visibility:hidden;height:0;overflow:hidden;content:".";} 
 .f-cb{zoom:1;} 
 .f-cb .topSearch{ float: left; margin-top: 10px; line-height: 30px; font-size: 12px; } 
 </style> 
</head> 
<body id="myTestCtrl" ng-controller="myTestCtrl"> 
<div class="wrapper"> 
 <div class="content"> 
  <div class="f-cb" style="height: 40px;"> 
   <div class="topSearch"><span class="w70 tr dib fl">主视觉图:</span><input type="text" class="inputBox fl ml5" ng-model="fileName"><button class="btn btn-primary ml10" ng-class="{'bg-bbbbbb':imgDisabled}" style="width:60px; margin-top:-3px; height:18px; position: relative;" img-upload></button></div> 
  </div> 
  <div class="f-cb mt10"><img ng-src="{{thumb.imgSrc}}" style="width:200px; height: 200px;" ng-show="thumb.imgSrc"/></div> 
 </div> 
 <div class="mt20 ml30"> 
  <button class="btn btn-primary" ng-click="saveClick()" ng-class="{'bg-bbbbbb':submitDisabled}">提交</button> 
 </div> 
</div> 
</body> 
</html> 
<span style="font-size:14px;">myCtrl.js:</span> 
<pre name="code" class="javascript">//关键 js 部分 
var myTestCtrl = angular.module('myTestCtrl', []); 
//定义“上传”指令,修改后也可用于上传其他类型的文件 
myTestCtrl.directive("imgUpload",function(){ 
 return{ 
  //通过设置项来定义 
  restrict: 'AE', 
  scope: false, 
  template: '<div class="fl"><input type="button" id="storeBtn" style="padding:0; position: absolute; top: 0; left: 0; background: none; border: none;color: #fff; width:84px; height: 30px; line-height: 30px;" value="选择文件"><input type="file" name="testReport" id="file" ng-disabled="imgDisabled" style="position: absolute; top: 0; left: 0; opacity: 0;height: 30px;" accept=".jpg,.png"></div>', //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; 
     return false; 
    } 
    scope.fileName = scope.file[0].name; 
    var postfix = scope.fileName.substring(scope.fileName.lastIndexOf(".")+1).toLowerCase(); 
    if(postfix !="jpg" && postfix !="png"){ 
     alert("图片仅支持png、jpg类型的文件"); 
     scope.fileName = ""; 
     scope.file = null; 
     scope.$apply(); 
     return false; 
    } 
    scope.$apply(); 
    scope.reader = new FileReader(); //创建一个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; 
  var url = '';//接口路径 
  var fd = new FormData(); 
  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; 
  }); 
 }; 
});
</pre>
<br> 
<pre></pre> 
<p></p> 
<pre>
</pre> 
<p></p> 
<pre>
</pre>

关于angularjs的知识大家可以参考下小编给大家整理的专题,angularjs学习笔记,一起看看吧!

以上所述是小编给大家介绍的AngularJs上传前预览图片的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Javascript 相关文章推荐
javascript中bind函数的作用实例介绍
Sep 28 Javascript
JavaScript自定义数组排序方法
Feb 12 Javascript
JQuery中clone方法复制节点
May 18 Javascript
非常酷炫的Bootstrap图片轮播动画
May 27 Javascript
郁闷!ionic中获取ng-model绑定的值为undefined如何解决
Aug 27 Javascript
微信 java 实现js-sdk 图片上传下载完整流程
Oct 21 Javascript
webpack打包后直接访问页面图片路径错误的解决方法
Jun 17 Javascript
JavaScript中Hoisting详解 (变量提升与函数声明提升)
Aug 18 Javascript
vue-cli + sass 的正确打开方式图文详解
Oct 27 Javascript
关于vue表单提交防双/多击的例子
Oct 31 Javascript
jQuery带控制按钮轮播图插件
Jul 31 jQuery
Vue使用鼠标在Canvas上绘制矩形
Dec 24 Vue.js
详解JavaScript中this的指向问题
Jan 20 #Javascript
详解微信小程序入门五: wxml文件引用、模版、生命周期
Jan 20 #Javascript
浅谈JavaScript异步编程
Jan 20 #Javascript
JavaScript实现事件的中断传播和行为阻止方法示例
Jan 20 #Javascript
小程序开发实战:实现九宫格界面的导航的代码实现
Jan 19 #Javascript
BootStrap组件之进度条的基本用法
Jan 19 #Javascript
微信小程序 页面跳转和数据传递实例详解
Jan 19 #Javascript
You might like
在PHP中利用XML技术构造远程服务(下)
2006/10/09 PHP
Smarty变量调节器失效的解决办法
2014/08/20 PHP
php中base_convert()进制数字转换函数实例
2014/11/20 PHP
PHP+JS三级菜单联动菜单实现方法
2016/02/24 PHP
PHP模版引擎原理、定义与用法实例
2019/03/29 PHP
学习ExtJS Window常用方法
2009/10/07 Javascript
JavaScript中判断函数是new还是()调用的区别说明
2011/04/07 Javascript
鼠标移到图片上变大显示而不是放大镜效果
2014/06/15 Javascript
jQuery实现列表的全选功能
2015/03/18 Javascript
使用jQuery在对象中缓存选择器的简单方法
2015/06/30 Javascript
浅谈JavaScript 的执行顺序
2015/08/07 Javascript
分享有关jQuery中animate、slide、fade等动画的连续触发、滞后反复执行的bug
2016/01/10 Javascript
微信小程序 SocketIO 实例讲解
2016/10/13 Javascript
小程序开发实战:实现九宫格界面的导航的代码实现
2017/01/19 Javascript
js 将input框中的输入自动转化成半角大写(税号输入框)
2017/02/16 Javascript
js利用for in循环获取 一个对象的所有属性以及值的实例
2017/03/30 Javascript
Vue2.0基于vue-cli+webpack同级组件之间的通信教程(推荐)
2017/09/14 Javascript
推荐VSCode 上特别好用的 Vue 插件之vetur
2017/09/14 Javascript
nodejs基于mssql模块连接sqlserver数据库的简单封装操作示例
2018/01/05 NodeJs
React学习之受控组件与数据共享实例分析
2020/01/06 Javascript
node.js中 mysql 增删改查操作及async,await处理实例分析
2020/02/11 Javascript
Python3.6正式版新特性预览
2016/12/15 Python
python导出chrome书签到markdown文件的实例代码
2017/12/27 Python
python将类似json的数据存储到MySQL中的实例
2019/07/12 Python
Python单元测试与测试用例简析
2019/11/09 Python
python实现图像拼接
2020/03/05 Python
python-地图可视化组件folium的操作
2020/12/14 Python
Harrods美国:英国最大的百货公司
2018/11/04 全球购物
个人实用简单的自我评价
2013/10/19 职场文书
小学数学课后反思
2014/04/23 职场文书
先进学校事迹材料
2014/12/30 职场文书
导游词之无锡华莱坞
2019/12/02 职场文书
SpringBoot2 参数管理实践之入参出参与校验的方式
2021/06/16 Java/Android
Java数据结构之链表相关知识总结
2021/06/18 Java/Android
宝塔更新Python及Flask项目的部署
2022/04/11 Python
以MySQL5.7为例了解一下执行计划
2022/04/13 MySQL