1.安装插件
### Bower ``` bower install angular-file-upload
### NPM ``` npm install angular-file-upload
2.插件使用
(1)html文件
<div class="iBox-content" ng-controller="uploadController"> <div class="row m-t imageFile"> <form class="form-horizontal" name="form"> <div class="form-line" style="margin-bottom: 15px;"> <label>请选择图片:</label><span class="small-tip"></span> <button class="btn btn-w-m btn-info" type="button" style="margin-left: 150px;margin-bottom: 15px;" ng-click="UploadFile('banner-upload')">点击上传图片 </button> <div class="choose-file-area"> <input class="file-name" type="text" readonly="readonly" ng-model="fileItem.name"/> <a href="javascript:;" class="choose-book"> <input type="file" name="certificate" nv-file-select uploader="uploader" ng-click="clearItems()"/>浏览 </a> </div> </div> <div class="col-md-6"> <img class="display-image" ng-if="image" ng-src="{{image}}" alt=""> </div> </form> </div> </div>
(2)通用js文件
angular.module('myApp.controllers') .controller('uploadController',['$scope','ApiConfig','FileUploader','$timeout','$rootScope','notify',function ($scope,ApiConfig,FileUploader,$timeout,$rootScope,notify) { var serverUrl = ApiConfig.API_HOST + "/admin/users/upload_avatar"; //定义两个上传后返回的状态,成功或失败 $scope.uploadStatus = false; $scope.broadcastName = ''; var uploader = $scope.uploader = new FileUploader({ url: serverUrl,queueLimit: 1,//文件个数 removeAfterUpload: true //上传后删除文件 }); $scope.clearItems = function () { //重新选择文件时,清空队列,达到覆盖文件的效果 uploader.clearQueue(); }; // uploader.onAfterAddingFile = function (fileItem) { // $scope.fileItem = fileItem._file; //添加文件之后,把文件信息赋给scope // //能够在这里判断添加的文件名后缀和文件大小是否满足需求。 // console.info('onAfterAddingFile',fileItem); // }; uploader.onAfterAddingFile = function (fileItem) { $scope.fileItem = fileItem._file; //添加文件之后,把文件信息赋给scope // console.info('onAfterAddingFile',fileItem); var fileReader = new FileReader(); fileReader.readAsDataURL(fileItem._file); var loadFile = function (fileReader,index) { fileReader.onload = function (e) { $timeout(function () { $scope.image = e.target.result; }); }; }(fileReader); }; uploader.onSuccessItem = function (fileItem,response,status,headers) { $scope.uploadStatus = true; //上传成功则把状态改为true if (response.data.Location) { $rootScope.$broadcast($scope.broadcastName,{ imgUrl: response.data.Location }); } notify({ message: response.status.message,position: $rootScope.globalData.notify_position,duration: $rootScope.globalData.notify_duration }); }; $scope.UploadFile = function (broadcastName) { uploader.uploadAll(); $scope.broadcastName = broadcastName; } }]);
(3)与html对应的controller文件
$rootScope.$on('banner-upload',function (event,option) { console.log('banner-upload'); $scope.data.bannerDetail.banner_url_big = option.imgUrl; });