代码之家  ›  专栏  ›  技术社区  ›  Varun.S

如何使用AngularJS获取文件资源管理器中所选文件的URL

  •  0
  • Varun.S  · 技术社区  · 6 年前

    我需要点击选择文件并从文件资源管理器中选择文件,然后我需要获取所选文件的URL并将其存储在变量中。你能看看下面的代码并指导我,因为我是AnularJS的新手…提前谢谢。

    <!DOCTYPE html>
    <html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <body >
        <div ng-app = "myApp" ng-controller="myControl">
            <input type="file" file-model="myFile" ng-module = "file_name" ng-click = "file_name()"><br>
            <h1>{{file_name()}}</h1>
        </div>
    
        <script>
            var app= angular.module("myApp",[]);
            app.controller("myControl",function($scope){
                $scope.file_name = function(){
                    return $scope.file_name;
                };
            });
    
        </script>
    </body>
    </html>
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Slava Utesinov    6 年前

    url directive $watch file_name

    angular.module('app', [])
      .controller('ctrl', ['$scope', function($scope) {
        $scope.$watch('file_url', function(newVal, oldVal) {
          if (newVal != oldVal)
            console.log(newVal);
        }, true)
      }])
      .directive('url', function() {
        return {
          restrict: 'A',
          scope: {
            url: '='
          },
          link: function(scope, element) {
            element.on('change', function(event) {
              var reader = new FileReader();
              reader.onloadend = function() {
                scope.$apply(function() {
                  scope.url = reader.result;
                });
              }
    
              var file = element[0].files[0];
              if (file)
                reader.readAsDataURL(file);
            })
          }
        }
      })
    <script src="//code.angularjs.org/snapshot/angular.min.js"></script>
    
    <div ng-app='app' ng-controller="ctrl">
      <img src="{{file_url}}" height="150" alt="Image preview...">
      <input type="file" url='file_url'>
    </div>