angularjs手機webapp 利用input拍照,相簿選擇、縮圖顯示 上傳圖片(一)
阿新 • • 發佈:2018-11-11
執行後的截圖:
html程式碼
<ul class="list_img"> <li ng-repeat="imageSrc in imgshows track by $index"> <img ng-src="{{imageSrc}}" alt=""> <i ng-click="DeleteImg($index, imgshows)" class=" fa fa-times del"></i> </li> <li class="add_btn" ng-click="shareCapture.addimage(1)" ng-if="imgshows.length<=2"> <img src="././static/img/plus.png" alt=""> <div class="file-box" > <input type="file" name="file" file-model="myFile" accept="image/*" class="file-btn"/> <div>上傳截圖</div> </div> </li> </ul>
js程式碼
自定一個指令directive
function fileModel ( $parse ) { return { restrict : 'A', link : function ( scope, element, attrs, ngModel ) { var model = $parse(attrs.fileModel); var modelSetter = model.assign; element.bind('change', function ( event ) { scope.$apply(function () { modelSetter(scope, element[ 0 ].files[ 0 ]); }); scope.file = (event.srcElement || event.target).files[ 0 ]; scope.getFile(scope.file); // $('#uploadfile').val(''); //發現拍照上傳後再次拍照不會呼叫change方法,加入這行程式碼可解決 }); } }; }
上傳函式controller
$scope.getFile = function ( file ) { console.info(file) Upload.upload({ url : photoUrl,//上傳服務的地址 data : {//上傳的資料引數 photoFile : file } }) .then(function ( resp ) { var fileUrl = resp.data; $scope.imgshows.push(fileUrl.object.showImage); }, function ( resp ) { console.log(resp.data, "上傳失敗"); }, function ( evt ) {//上傳進度顯示 var progressPercentage = parseInt(100.0 * evt.loaded / evt.total); console.log('progress: ' + progressPercentage + '% '); }); };
刪除圖片函式
DeleteImg : function ( index, imgs ) { $scope.imgshows.splice(index, 1); }
圖片上傳成功了,剩下的就是儲存你上傳的圖片了,這個功能很簡單了,直接拿到需要儲存的引數資料,調取介面,進行提交就OK啦
angular .module('uploadimg') .directive('fileModel', fileModel) .controller('shareCaptureCtrl', shareCaptureCtrl);