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 相关文章推荐
新浪中用来显示flash的函数
Apr 02 Javascript
JQUERY的属性选择符和自定义选择符使用方法(二)
Apr 07 Javascript
多个表单中如何获得这个文件上传的网址实现js代码
Mar 25 Javascript
当某个文本框成为焦点时即清除文本框内容
Apr 28 Javascript
实例详解AngularJS实现无限级联动菜单
Jan 15 Javascript
BootStrap学习系列之Bootstrap Typeahead 组件实现百度下拉效果(续)
Jul 07 Javascript
浅谈javascript中关于日期和时间的基础知识
Jul 13 Javascript
JS中使用FormData上传文件、图片的方法
Aug 07 Javascript
JavaScript设计模式之工厂模式简单实例教程
Jul 03 Javascript
JS打印彩色菱形的实例代码
Aug 15 Javascript
Vue+ElementUI项目使用webpack输出MPA的方法
Aug 27 Javascript
JS实现简单控制视频播放倍速的实例代码
Apr 18 Javascript
详解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
7个鲜为人知却非常实用的PHP函数
2015/07/01 PHP
javascript 中对象的继承〔转贴〕
2007/01/22 Javascript
JavaScript中的集合及效率
2010/01/08 Javascript
JavaScript Scoping and Hoisting 翻译
2012/07/03 Javascript
ie下$.getJSON出现问题的解决方法
2014/02/12 Javascript
JQuery动画与特效实例分析
2015/02/02 Javascript
Javascript实现的简单右键菜单类
2015/09/23 Javascript
详解nodejs与javascript中的aes加密
2016/05/22 NodeJs
jQuery中each循环的跳出和结束实例
2017/08/16 jQuery
JS点击图片弹出文件选择框并覆盖原图功能的实现代码
2017/08/25 Javascript
JS模拟实现哈希表及应用详解
2018/05/04 Javascript
vue实现条件判断动态绑定样式的方法
2018/09/29 Javascript
jQuery高级编程之js对象、json与ajax用法实例分析
2019/11/01 jQuery
python实现ftp客户端示例分享
2014/02/17 Python
python实现折半查找和归并排序算法
2017/04/14 Python
Python使用cx_Freeze库生成msi格式安装文件的方法
2018/07/10 Python
在python中使用with打开多个文件的方法
2019/01/07 Python
Python使用Shelve保存对象方法总结
2019/01/28 Python
使用Python中的reduce()函数求积的实例
2019/06/28 Python
将pymysql获取到的数据类型是tuple转化为pandas方式
2020/05/15 Python
Pycharm安装并配置jupyter notebook的实现
2020/05/18 Python
Tensorflow tf.tile()的用法实例分析
2020/05/22 Python
Python中过滤字符串列表的方法
2020/12/22 Python
使用CSS3的font-face字体嵌入样式的方法讲解
2016/05/13 HTML / CSS
Avène雅漾美国官方网站:敏感肌肤护理专家
2016/10/24 全球购物
印度在线杂货店:bigbasket
2018/08/23 全球购物
NBA欧洲商店(西班牙):NBA Europe Store ES
2019/04/16 全球购物
英文翻译的自我评价语句
2013/10/04 职场文书
仓库文员岗位职责
2014/04/06 职场文书
危爆物品安全大检查大整治工作方案
2014/05/03 职场文书
煤矿安全承诺书
2014/05/22 职场文书
销售人员求职信
2014/07/22 职场文书
交通处罚决定书
2015/06/24 职场文书
2015年计算机教师工作总结
2015/07/22 职场文书
PHP中->和=>的意思
2021/03/31 PHP
Java常用工具类汇总 附示例代码
2021/06/26 Java/Android