Read file txt

2

I am creating a WEB application and need to read a txt file that will be provided by the user. The code I'm using to read is not working and I can not find a way to read it elsewhere.

// Código dentro do controller
$scope.imprimir = function () {
  lerArquivoTxt.carregarArquivo();
}

// Código dentro do service
function _carregarArquivoTxt() {
  var arquivoSelecionado = document.getElementById('arquivoPastas');
  var divSaida = document.getElementById('textoLido');
  var fileExtension = /text.*/;
  var arquivoLeitura = arquivoSelecionado.files[0];
  var fileReader = new FileReader();
  fileReader.readAsText(arquivoLeitura);
  divSaida.innerText = 'resultado: ' + fileReader.result;
}
<div class="col-sm-6 form-group" id="arquivo">
<div class="lbltitulo" for="Numero">Selecione o arquivo base para criar as pastas do projeto:</div>
<div class="tbpdd16">
  <input  type="file" 
          id="arquivoPastas"
          class="hideBtn btn btn-warning">
</div>

<div class="">
  <input  type="text" 
          id="txtfiletoread" 
          class="form-control"
          placeholder="Pasta / sub pasta"
          ng-model="pasta.pasta">
</div>
<div id="textoLido"></div>

The idea is that the user select a file through the input file, the controller calls the function _loadTextTxt () from the service and this function read and return the whole file read. I need help with the code that reads the txt file.

    
asked by anonymous 22.08.2017 / 00:15

1 answer

2

To load the text of a .txt file with create a directive that at the time of changing input file will show text content in div , example :

var app = angular.module("app", []);
app.controller("ctrl", function($scope) {
  $scope.text = {
    value: 'Esperando ...'
  };  
});
app.directive("fileTxt", function() {
  return {
    require: "ngModel",
    scope: true,
    link: function(scope, elem, attrs, ngModel) {
      elem.on("change", function(e) {
        var reader = new FileReader();
        reader.onload = (function(reader) {
          return function() {
            scope.$apply(function() {
              scope.text.value = reader.result;            
            });        
            return reader.result;
          }
        })(reader);
        reader.readAsText(elem[0].files[0]);
      });      
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.0/angular.min.js"></script><divng-app="app" ng-controller="ctrl">
  <input type="file" file-txt ng-model="fileItem" name="fileTxt">
  <br />
  <br />
  <div>{{text.value}}</div>  
  
</div>

Do not forget to put the input file directive in your file-txt as follows:

 <input type="file" file-txt ng-model="fileItem" name="fileTxt">

22.08.2017 / 02:24