簡體   English   中英

FileReader 未使用 AngularJS 正確加載文件

[英]FileReader not loading file properly using AngularJS

我正在嘗試將 csv 文件加載到 AngularJS 中,以便我可以對內容進行一些操作。 它不像我想要的那樣有效。 為了測試它是否正確加載,我將它加載到文本區域以查看內容。

當我加載文件時,它說它已正確加載但 onload() 事件似乎沒有觸發,直到我加載第二個 CSV 文件,在這種情況下,第一個文件顯示在文本區域中。

HTML:

<div>
  <input ng-model="csv"
            onchange="angular.element(this).scope().fileChanged()"
            type="file" accept=".csv" id="fileInput"/>
</div>
<br/>
<div>
  <textarea ng-model="csvFile" readonly="true" style="width:99%; height:500px" disabled></textarea>
</div>

記者:

$scope.fileChanged = function() {

  $scope.$apply(function() {
      var csvFileInput = document.getElementById('fileInput');
      var reader = new FileReader();
      var csvFile = csvFileInput.files[0];
      reader.onload = function(e) {
          $scope.csvFile = reader.result;
      };
      reader.readAsText(csvFile);
  });
};

當我將其放入 JSFiddle 時,該文件根本不會出現在文本區域中。 我是 JSFiddle 的新手,所以我不知道為什么會這樣。

任何幫助都將不勝感激。

重新排序代碼的某些行,希望評論足夠解釋

$scope.fileChanged = function() {

  // define reader
  var reader = new FileReader();

  // A handler for the load event (just defining it, not executing it right now)
  reader.onload = function(e) {
      $scope.$apply(function() {
          $scope.csvFile = reader.result;
      });
  };

  // get <input> element and the selected file 
  var csvFileInput = document.getElementById('fileInput');    
  var csvFile = csvFileInput.files[0];

  // use reader to read the selected file
  // when read operation is successfully finished the load event is triggered
  // and handled by our reader.onload function
  reader.readAsText(csvFile);
};

參考: MDN的FileReader

這只是HTML的一個小改進:

<input type="file" onchange="angular.element(this).scope().file_changed(this)"/>
<textarea cols="75" rows="15">{{ dataFile }}</textarea>

和控制器:

.controller('MyCtrl', ['$scope', function($scope) {
    var vm = $scope;

    vm.file_changed = function(element){
        var dataFile = element.files[0];
        var reader = new FileReader();
        reader.onload = function(e){
            vm.$apply(function(){
                vm.dataFile = reader.result;
            });
        };
        reader.readAsText(dataFile);
    };
}]);

參考

如果你不想使用$scope.$apply() ,你可以使用$timeout

const fileReader = new FileReader();
            
fileReader.onload = (event) => {
    this.$timeout(() => {
        // Logic goes here...
    }, 0);
};

...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM