如何在AngularJS中读取文件?

时间:2023-02-03 18:20:34

Is it possible to read files in AngularJS? I want to place the file into an HTML5 canvas to crop.

是否可以读取AngularJS中的文件?我想将文件放入HTML5画布中进行裁剪。

I was thinking of using a directive? This is the javscript code I want to put into my directive:

我在考虑使用指令?这是我想要放入我的指令的javscript代码:

function readURL(input) {

    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#blah').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

3 个解决方案

#1


26  

Yes, directives is a right way, but it looks little bit different:

是的,指令是正确的方式,但它看起来有点不同:

.directive("ngFileSelect",function(){    
  return {
    link: function($scope,el){          
      el.bind("change", function(e){          
        $scope.file = (e.srcElement || e.target).files[0];
        $scope.getFile();
      });          
    }        
  }
})

Working example: http://plnkr.co/edit/y5n16v?p=preview

工作示例:http://plnkr.co/edit/y5n16v?p = preview

Thanks to lalalalalmbda for this link.

感谢lalalalalmbda这个链接。

#2


10  

I've taken Cherniv's code and folded all of it into a directive:

我已经采用了切尔诺夫的代码并将其全部折叠成一个指令:

.directive('fileSelect', ['$window', function ($window) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, el, attr, ctrl) {
            var fileReader = new $window.FileReader();

            fileReader.onload = function () {
                ctrl.$setViewValue(fileReader.result);

                if ('fileLoaded' in attr) {
                    scope.$eval(attr['fileLoaded']);
                }
            };

            fileReader.onprogress = function (event) {
                if ('fileProgress' in attr) {
                    scope.$eval(attr['fileProgress'], 
                    {'$total': event.total, '$loaded': event.loaded});
                }
            };

            fileReader.onerror = function () {
                if ('fileError' in attr) {
                    scope.$eval(attr['fileError'], 
                    {'$error': fileReader.error});
                }
            };

            var fileType = attr['fileSelect'];

            el.bind('change', function (e) {
                var fileName = e.target.files[0];

                if (fileType === '' || fileType === 'text') {
                    fileReader.readAsText(fileName);
                } else if (fileType === 'data') {
                    fileReader.readAsDataURL(fileName);
                }
            });
        }
    };
}]);

You can then use the directive as follows:

然后,您可以按如下方式使用该指令:

<input type="file" ng-model="file.data" 
       file-select="data" 
       file-loaded="myLoaded()"
       file-error="myError($error)" 
       file-progress="myProgress($total,$loaded)">

Where "file.data", "myLoaded", "myError", and "myProgress" are in the enclosing scope.

其中“file.data”,“myLoaded”,“myError”和“myProgress”位于封闭范围内。

#3


1  

Angular File reader.

角度文件阅读器。

link: function(scope, element, attrs) {
            element.on('change', function(e) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    scope.$apply(function() {
                       scope.onReadFile({$content:e.target.result});
                    });
                };
                reader.readAsText((e.srcElement || e.target).files[0]);
            });
        }

Live example : Live Run On Plunker

实例:在Plunker上直播

#1


26  

Yes, directives is a right way, but it looks little bit different:

是的,指令是正确的方式,但它看起来有点不同:

.directive("ngFileSelect",function(){    
  return {
    link: function($scope,el){          
      el.bind("change", function(e){          
        $scope.file = (e.srcElement || e.target).files[0];
        $scope.getFile();
      });          
    }        
  }
})

Working example: http://plnkr.co/edit/y5n16v?p=preview

工作示例:http://plnkr.co/edit/y5n16v?p = preview

Thanks to lalalalalmbda for this link.

感谢lalalalalmbda这个链接。

#2


10  

I've taken Cherniv's code and folded all of it into a directive:

我已经采用了切尔诺夫的代码并将其全部折叠成一个指令:

.directive('fileSelect', ['$window', function ($window) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, el, attr, ctrl) {
            var fileReader = new $window.FileReader();

            fileReader.onload = function () {
                ctrl.$setViewValue(fileReader.result);

                if ('fileLoaded' in attr) {
                    scope.$eval(attr['fileLoaded']);
                }
            };

            fileReader.onprogress = function (event) {
                if ('fileProgress' in attr) {
                    scope.$eval(attr['fileProgress'], 
                    {'$total': event.total, '$loaded': event.loaded});
                }
            };

            fileReader.onerror = function () {
                if ('fileError' in attr) {
                    scope.$eval(attr['fileError'], 
                    {'$error': fileReader.error});
                }
            };

            var fileType = attr['fileSelect'];

            el.bind('change', function (e) {
                var fileName = e.target.files[0];

                if (fileType === '' || fileType === 'text') {
                    fileReader.readAsText(fileName);
                } else if (fileType === 'data') {
                    fileReader.readAsDataURL(fileName);
                }
            });
        }
    };
}]);

You can then use the directive as follows:

然后,您可以按如下方式使用该指令:

<input type="file" ng-model="file.data" 
       file-select="data" 
       file-loaded="myLoaded()"
       file-error="myError($error)" 
       file-progress="myProgress($total,$loaded)">

Where "file.data", "myLoaded", "myError", and "myProgress" are in the enclosing scope.

其中“file.data”,“myLoaded”,“myError”和“myProgress”位于封闭范围内。

#3


1  

Angular File reader.

角度文件阅读器。

link: function(scope, element, attrs) {
            element.on('change', function(e) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    scope.$apply(function() {
                       scope.onReadFile({$content:e.target.result});
                    });
                };
                reader.readAsText((e.srcElement || e.target).files[0]);
            });
        }

Live example : Live Run On Plunker

实例:在Plunker上直播