如何在 AngularJS 中获取文件内容和其他详细信息

How to get file content and other details in AngularJS

如何在单击提交按钮时获取文件内容。我只得到第一个和第二个输入。 请参考片段:

!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="formCtrl">
  <form novalidate>
    First Name:<br>
    <input type="text" ng-model="user.firstName"><br>
    Last Name:<br>
    <input type="text" ng-model="user.lastName">
    <input type="file" ng-model="user.file">
    <br><br>
    <button ng-click="reset()">Submit</button>
  </form>
  <p>form = {{user}}</p>
  <p>master = {{master}}</p>
</div>
  <script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
   $scope.reset = function(){
   console.log($scope.user)
   }
   
});
</script>

</body>
</html>

我使用指令来处理表单中的文件(正如 joakimbl 在 the answer here 中所建议的):

app.directive('validFile',[function() {
  return {
    require : 'ngModel',
    scope : {format: '@', upload : '&upload'},
    link : function(scope, el, attrs, ngModel) {
      // change event is fired when file is selected
      el.bind('change', function(event) {
        console.log(event.target.files[0]);
        scope.upload({file:event.target.files[0]});
        scope.$apply(function() {
          ngModel.$setViewValue(el.val());
          ngModel.$render();
        });
      })
    }
  }
}]);

在你的 HTML

<input type="file" valid-file upload="uploadFile(file)" ng-model="file">

此处 uploadFile 将是您控制器中的一个函数,您可以在其中获取文件的内容

控制器代码

$scope.uploadFile = function(element) {
    $scope.user.file = element;
    console.log($scope.user);
  }

请看这个plunker

您无法使用 ng-scopes 直接访问文件内容,但您可以使用本机 JavaScript FileAPI. Here is a working fiddle 读取文件内容。我认为您想显示文件内容而不在服务器端上传它们。这不是 100% 清楚你想要什么,所以这就是你如何获得 filecontentfilesizefilename在浏览器中,无需上传。

查看

<div ng-controller="MyCtrl">
  <input type="file" id="myFileInput" />
  <br /><br />
  <button ng-click="submit()">
    Submit
  </button>
  <br /><br />
  <br /><br />
  <h1>
    Filename: {{ fileName }}
  </h1>
  <h2>
    File size: {{ fileSize }} Bytes
  </h2>
  <h2>
    File Content: {{ fileContent }}
  </h2>
</div>

AngularJS 应用

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($scope) {
    $scope.fileContent = '';
    $scope.fileSize = 0;
    $scope.fileName = '';
    $scope.submit = function () {
      var file = document.getElementById("myFileInput").files[0];
      if (file) {
        var aReader = new FileReader();
        aReader.readAsText(file, "UTF-8");
        aReader.onload = function (evt) {
            $scope.fileContent = aReader.result;
            $scope.fileName = document.getElementById("myFileInput").files[0].name;
            $scope.fileSize = document.getElementById("myFileInput").files[0].size;;
        }
        aReader.onerror = function (evt) {
            $scope.fileContent = "error";
        }
      }
    }
});