• home > webfront > ECMAS > angularjs >

    angularjs用file input上传图片详解

    Author:zhoulujun Date:

    angular 上传图片,但是filechange并angular并不鸟 ng-change事件。这是为啥呢?因为,ng-change,里面的$event事件,被angular重新覆盖

    angular 上传图片,但是filechange并angular并不鸟 ng-change事件。

     这是为啥呢?

    因为,ng-change,里面的$event事件,被angular重新覆盖了,看这段代码:

    var ngChangeDirective = valueFn({
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, element, attr, ctrl) {
        ctrl.$viewChangeListeners.push(function() {
          scope.$eval(attr.ngChange);
        });
      }
    });

    Screen Shot 2017-07-17 at 17.00.35.png

    所以,上传图片,只好在原生的基础上:

    <input type="file"  onchange="angular.element(this).scope().fileNameChanged(this)"  accept="image/png, image/jpeg">
    <img ng-src={{imgBase64}} style="max-width:300px;max-height:300px;margin:0 auto;display:block;" />
    
    $scope.fileNameChanged = function (e) {
        var file=e.files[0];
        var reader=new FileReader();
        reader.readAsDataURL(file);
        reader.onload=function () {
            $scope.imgBase64=reader.result;
            $scope.$apply();
        };
    
    };


    不过,不过,有造好的轮子:

    Angular File Upload is a module for the AngularJS framework. Supports drag-n-drop upload, upload progress, validation filters and a file upload queue. It supports native HTML5 uploads, but degrades to a legacy iframe upload method for older browsers. Works with any server side platform which supports standard HTML form uploads. 

    用的时候:

    <input type="file" nv-file-select uploader="uploader"/>
    <input type="file" nv-file-select uploader="uploader"/><br/>
    <ul>
        <li ng-repeat="item in uploader.queue">
           <div> Name: <span ng-bind="item.file.name"></span></div>
            <div ng-show="uploader.isHTML5" ng-thumb="{ file: item._file, height: 100 }"></div>
    
            <div><button ng-click="item.upload()">upload</button></div>
        </li>
    </ul>
    
    <div>
        <button type="button" class="btn btn-success btn-s" ng-click="uploader.uploadAll()" ng-disabled="!uploader.getNotUploadedItems().length">
            Upload all
        </button>
        <button type="button" class="btn btn-warning btn-s" ng-click="uploader.cancelAll()" ng-disabled="!uploader.isUploading" disabled="disabled">
            Cancel all
        </button>
        <button type="button" class="btn btn-danger btn-s" ng-click="uploader.clearQueue()" ng-disabled="!uploader.queue.length">
            Remove all
        </button>
    </div>
    
    
    var uploader = $scope.uploader = new FileUploader({
        // url: 'http://localhost:8080/服务器',
    
        //     url {String}: Path on the server to upload files
        // alias {String}: Name of the field which will contain the file, default is file
        // queue {Array}: Items to be uploaded
        // progress {Number}: Upload queue progress percentage. Read only.
        //     headers {Object}: Headers to be sent along with the files. HTML5 browsers only.
        //     formData {Array}: Data to be sent along with the files
        // filters {Array}: Filters to be applied to the files before adding them to the queue. If the filter returns true the file will be added to the queue
        // autoUpload {Boolean}: Automatically upload files after adding them to the queue
        // method {String}: It's a request method. By default POST. HTML5 browsers only.
        // removeAfterUpload {Boolean}: Remove files from the queue after uploading
        // isHTML5 {Boolean}: true if uploader is html5-uploader. Read only.
        //     isUploading {Boolean}: true if an upload is in progress. Read only.
        //     queueLimit {Number} : maximum count of files
        // withCredentials {Boolean} : enable CORS. HTML5 browsers only.
    });
    
    //过滤器
    uploader.filters.push({
        name: 'yourName2',
        fn: function (item) {
    
    
            return this.queue.length < 10;
        }
    });
    
    // CALLBACKS
    
    uploader.onWhenAddingFileFailed = function (item /*{File|FileLikeObject}*/, filter, options) {
        console.info('onWhenAddingFileFailed', item, filter, options);
    };
    uploader.onAfterAddingFile = function (fileItem) {
        console.info('onAfterAddingFile', fileItem);
    };
    uploader.onAfterAddingAll = function (addedFileItems) {
        console.info('onAfterAddingAll', addedFileItems);
    };
    uploader.onBeforeUploadItem = function (item) {
        console.info('onBeforeUploadItem', item);
    };
    uploader.onProgressItem = function (fileItem, progress) {
        console.info('onProgressItem', fileItem, progress);
    };
    uploader.onProgressAll = function (progress) {
        console.info('onProgressAll', progress);
    };
    uploader.onSuccessItem = function (fileItem, response, status, headers) {
        console.info('onSuccessItem', fileItem, response, status, headers);
    };
    uploader.onErrorItem = function (fileItem, response, status, headers) {
        console.info('onErrorItem', fileItem, response, status, headers);
    };
    uploader.onCancelItem = function (fileItem, response, status, headers) {
        console.info('onCancelItem', fileItem, response, status, headers);
    };
    uploader.onCompleteItem = function (fileItem, response, status, headers) {
        console.info('onCompleteItem', fileItem, response, status, headers);
    };
    uploader.onCompleteAll = function () {
        console.info('onCompleteAll');
    };


    如果,要家预览,记得,要添加,

    .directive('ngThumb', ['$window', function($window) {
        var helper = {
            support: !!($window.FileReader && $window.CanvasRenderingContext2D),
            isFile: function(item) {
                return angular.isObject(item) && item instanceof $window.File;
            },
            isImage: function(file) {
                var type =  '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|';
                return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
            }
        };
    
        return {
            restrict: 'A',
            template: '<canvas/>',
            link: function(scope, element, attributes) {
                if (!helper.support) return;
    
                var params = scope.$eval(attributes.ngThumb);
    
                if (!helper.isFile(params.file)) return;
                if (!helper.isImage(params.file)) return;
    
                var canvas = element.find('canvas');
                var reader = new FileReader();
    
                reader.onload = onLoadFile;
                reader.readAsDataURL(params.file);
    
                function onLoadFile(event) {
                    var img = new Image();
                    img.onload = onLoadImage;
                    img.src = event.target.result;
                }
    
                function onLoadImage() {
                    var width = params.width || this.width / this.height * params.height;
                    var height = params.height || this.height / this.width * params.width;
                    canvas.attr({ width: width, height: height });
                    canvas[0].getContext('2d').drawImage(this, 0, 0, width, height);
                }
            }
        };
    }])



    转载本站文章《angularjs用file input上传图片详解》,
    请注明出处:https://www.zhoulujun.cn/html/webfront/ECMAScript/angularjs/2017_0717_8033.html