AngularJs上傳前預覽圖片的執行個體代碼,

來源:互聯網
上載者:User

AngularJs上傳前預覽圖片的執行個體代碼,

在工作中,使用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上傳前預覽圖片的執行個體代碼,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對幫客之家網站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.