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; });
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。