通過AngularJS實現(xiàn)圖片上傳及縮略圖展示示例
更新時間:2017年01月03日 15:14:31 作者:程序大大
本篇文章主要介紹了通過AngularJS實現(xiàn)圖片上傳及縮略圖展示,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
通過AngularJS實現(xiàn)圖片上傳及縮略圖展示示例,廢話不多說了,具體如下:
從項目中截出的代碼
HTML部分:
<section> <img src="image/user-tuijian/tuijian_banner.png" /> <div> <form ng-submit="submit_form()"> <input type="text" name="aaa" placeholder="商品名稱:" ng-model="form.goods_name" /> <input type="text" name="bbb" placeholder="商品網(wǎng)址:" ng-model="form.goods_url" /> <textarea placeholder="您寶貴的留言就是我們前進的動力!" ng-model="form.user_msg"></textarea> <div> <div ng-repeat="item in thumb"> <!-- 采用angular循環(huán)的方式,對存入thumb的圖片進行展示 --> <label> <img ng-src="{{item.imgSrc}}"/> </label> <span ng-if="item.imgSrc" ng-click="img_del($index)"></span> </div> <div ng-repeat="item in thumb_default"> <!-- 這里之所以寫個循環(huán),是為了后期萬一需要多個‘加號'框 --> <label> <input type="file" id="one-input" accept="image/*" file-model="images" onchange="angular.element(this).scope().img_upload(this.files)"/> </label> </div> </div> <p>(*^_^*)請詳細描述您的需求,有助于我們快速定位并解決問題,希望我們的產(chǎn)品和服務能得到您的肯定。</p> <input type="submit" name="" value="提 交" /> </form> </div> </section>
JS部分:
Module.controller('controlName', ['$scope', '$http', function($scope, $http) { $scope.reader = new FileReader(); //創(chuàng)建一個FileReader接口 $scope.form = { //用于綁定提交內(nèi)容,圖片或其他數(shù)據(jù) image:{}, }; $scope.thumb = {}; //用于存放圖片的base64 $scope.thumb_default = { //用于循環(huán)默認的‘加號'添加圖片的框 1111:{} }; $scope.img_upload = function(files) { //單次提交圖片的函數(shù) $scope.guid = (new Date()).valueOf(); //通過時間戳創(chuàng)建一個隨機數(shù),作為鍵名使用 $scope.reader.readAsDataURL(files[0]); //FileReader的方法,把圖片轉(zhuǎn)成base64 $scope.reader.onload = function(ev) { $scope.$apply(function(){ $scope.thumb[$scope.guid] = { imgSrc : ev.target.result, //接收base64 } }); }; var data = new FormData(); //以下為像后臺提交圖片數(shù)據(jù) data.append('image', files[0]); data.append('guid',$scope.guid); $http({ method: 'post', url: '/comm/test-upload.php?action=success', data:data, headers: {'Content-Type': undefined}, transformRequest: angular.identity }).success(function(data) { if (data.result_code == 'SUCCESS') { $scope.form.image[data.guid] = data.result_value; $scope.thumb[data.guid].status = 'SUCCESS'; console.log($scope.form) } if(data.result_code == 'FAIL'){ console.log(data) } }) }; $scope.img_del = function(key) { //刪除,刪除的時候thumb和form里面的圖片數(shù)據(jù)都要刪除,避免提交不必要的 var guidArr = []; for(var p in $scope.thumb){ guidArr.push(p); } delete $scope.thumb[guidArr[key]]; delete $scope.form.image[guidArr[key]]; }; $scope.submit_form = function(){ //圖片選擇完畢后的提交,這個提交并沒有提交前面的圖片數(shù)據(jù),只是提交用戶操作完畢后, 到底要上傳哪些,通過提交鍵名或者鏈接,后臺來判斷最終用戶的選擇,整個思路也是如此 $http({ method: 'post', url: '/comm/test.php', data:$scope.form, }).success(function(data) { console.log(data); }) }; }]);
最后的效果如圖:
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。