ng-model for `<input type=“file”/>` (with directive DEMO)

后端 未结 12 2298
北恋
北恋 2020-11-21 06:40

I tried to use ng-model on input tag with type file:


But after selecting a file, in

12条回答
  •  面向向阳花
    2020-11-21 06:44

    I use this directive:

    angular.module('appFilereader', []).directive('appFilereader', function($q) {
        var slice = Array.prototype.slice;
    
        return {
            restrict: 'A',
            require: '?ngModel',
            link: function(scope, element, attrs, ngModel) {
                    if (!ngModel) return;
    
                    ngModel.$render = function() {};
    
                    element.bind('change', function(e) {
                        var element = e.target;
    
                        $q.all(slice.call(element.files, 0).map(readFile))
                            .then(function(values) {
                                if (element.multiple) ngModel.$setViewValue(values);
                                else ngModel.$setViewValue(values.length ? values[0] : null);
                            });
    
                        function readFile(file) {
                            var deferred = $q.defer();
    
                            var reader = new FileReader();
                            reader.onload = function(e) {
                                deferred.resolve(e.target.result);
                            };
                            reader.onerror = function(e) {
                                deferred.reject(e);
                            };
                            reader.readAsDataURL(file);
    
                            return deferred.promise;
                        }
    
                    }); //change
    
                } //link
        }; //return
    });
    

    and invoke it like this:

    
    

    The property (editItem.editItem._attachments_uri.image) will be populated with the contents of the file you select as a data-uri (!).

    Please do note that this script will not upload anything. It will only populate your model with the contents of your file encoded ad a data-uri (base64).

    Check out a working demo here: http://plnkr.co/CMiHKv2BEidM9SShm9Vv

提交回复
热议问题