Jak odczytać lokalny plik tekstowy?

Próbuję napisać prosty czytnik plików tekstowych, tworząc funkcję, która zajmuje ścieżkę pliku i konwertuje każdą linię tekstu do tablicy znaków, ale to nie działa.

function readTextFile() {
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", "testing.txt", true);
  rawFile.onreadystatechange = function() {
    if (rawFile.readyState === 4) {
      var allText = rawFile.responseText;
      document.getElementById("textSection").innerHTML = allText;
    }
  }
  rawFile.send();
}
Co tu się dzieje?

To nadal nie działa po zmianie kodu trochę z poprzednia wersja i teraz daje mi XMLHttpRequest wyjątek 101.

Testowałem to na Firefoksie i działa, ale w Google Chrome po prostu nie działa i ciągle daje ja wyjątek 101. Jak mogę to uruchomić nie tylko na Firefoksie, ale także na innych przeglądarkach (zwłaszcza Chrome)?
Author: Xufox, 2013-01-22

10 answers

Musisz sprawdzić status 0 (ponieważ podczas ładowania plików lokalnie za pomocą XMLHttpRequest, nie otrzymasz statusu zwróconego, ponieważ nie pochodzi on z Webserver)

function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                alert(allText);
            }
        }
    }
    rawFile.send(null);
}

I określ file:// w nazwie pliku:

readTextFile("file:///C:/your/path/to/file.txt");
 227
Author: Majid Laissi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-07 01:51:21

Visit Javascripture ! Przejdź do sekcji readAsText i wypróbuj przykład. Dowiesz się, jak działa readAsText Funkcja FileReader.

    <html>
    <head>
    <script>
      var openFile = function(event) {
        var input = event.target;

        var reader = new FileReader();
        reader.onload = function(){
          var text = reader.result;
          var node = document.getElementById('output');
          node.innerText = text;
          console.log(reader.result.substring(0, 200));
        };
        reader.readAsText(input.files[0]);
      };
    </script>
    </head>
    <body>
    <input type='file' accept='text/plain' onchange='openFile(event)'><br>
    <div id='output'>
    ...
    </div>
    </body>
    </html>
 64
Author: Amit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-21 04:49:41

Po wprowadzeniu API API w javascript, odczyt zawartości pliku nie może być prostszy.

Odczyt pliku tekstowego

fetch('file.txt')
  .then(response => response.text())
  .then(text => console.log(text))
  // outputs the content of the text file

Odczyt pliku json

fetch('file.json')
  .then(response => response.json())
  .then(jsonResponse => console.log(jsonResponse))     
   // outputs a javascript object from the parsed json
W tym celu prosimy o zapoznanie się z naszą polityką prywatności.]}

Ta technika działa dobrze w Firefox , ale wygląda na to, że implementacja Chrome nie obsługuje schematu URL file:/// w dniu pisania tej aktualizacji (testowany w Chrome 68).

 51
Author: Abdelaziz Mokhnache,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-30 22:26:02

var input = document.getElementById("myFile");
var output = document.getElementById("output");


input.addEventListener("change", function () {
  if (this.files && this.files[0]) {
    var myFile = this.files[0];
    var reader = new FileReader();
    
    reader.addEventListener('load', function (e) {
      output.textContent = e.target.result;
    });
    
    reader.readAsBinaryString(myFile);
  }   
});
<input type="file" id="myFile">
<hr>
<textarea style="width:500px;height: 400px" id="output"></textarea>
 18
Author: Poornachander K,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-22 10:46:37

Spróbuj utworzyć dwie funkcje:

function getData(){       //this will read file and send information to other function
       var xmlhttp;

       if (window.XMLHttpRequest) {
           xmlhttp = new XMLHttpRequest();               
       }           
       else {               
           xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");               
       }

       xmlhttp.onreadystatechange = function () {               
           if (xmlhttp.readyState == 4) {                   
             var lines = xmlhttp.responseText;    //*here we get all lines from text file*

             intoArray(lines);     *//here we call function with parameter "lines*"                   
           }               
       }

       xmlhttp.open("GET", "motsim1.txt", true);
       xmlhttp.send();    
}

function intoArray (lines) {
   // splitting all text data into array "\n" is splitting data from each new line
   //and saving each new line as each element*

   var lineArr = lines.split('\n'); 

   //just to check if it works output lineArr[index] as below
   document.write(lineArr[2]);         
   document.write(lineArr[3]);
}
 12
Author: Motsim Mansoor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-02 17:18:47

Inny przykład-mój czytelnik z klasą FileReader

<html>
    <head>
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
        <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
        <script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
    </head>
    <body>
        <script>
            function PreviewText() {
            var oFReader = new FileReader();
            oFReader.readAsDataURL(document.getElementById("uploadText").files[0]);
            oFReader.onload = function (oFREvent) {
                document.getElementById("uploadTextValue").value = oFREvent.target.result; 
                document.getElementById("obj").data = oFREvent.target.result;
            };
        };
        jQuery(document).ready(function(){
            $('#viewSource').click(function ()
            {
                var text = $('#uploadTextValue').val();
                alert(text);
                //here ajax
            });
        });
        </script>
        <object width="100%" height="400" data="" id="obj"></object>
        <div>
            <input type="hidden" id="uploadTextValue" name="uploadTextValue" value="" />
            <input id="uploadText" style="width:120px" type="file" size="10"  onchange="PreviewText();" />
        </div>
        <a href="#" id="viewSource">Source file</a>
    </body>
</html>
 11
Author: websky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-19 15:35:07

Jon Perryman,

Tak js może odczytywać pliki lokalne (patrz FileReader ()), ale nie automatycznie: użytkownik musi przekazać plik lub listę plików do skryptu za pomocą html <input type=file>.

Następnie za pomocą js można przetworzyć (przykładowy widok) plik lub listę plików, niektóre ich właściwości oraz zawartość pliku lub plików.

To, czego js nie może zrobić ze względów bezpieczeństwa, to uzyskać automatyczny dostęp (bez wejścia użytkownika) do systemu plików swojego komputera.

Aby umożliwić js aby automatycznie połączyć się z lokalnym fs, konieczne jest utworzenie Nie pliku html z js w środku, ale dokumentu hta.

Plik hta może zawierać js lub VBS wewnątrz niego.

Ale plik wykonywalny hta będzie działał tylko na systemach windows.

Jest to standardowe zachowanie przeglądarki.

Również google chrome pracował w fs api, więcej informacji tutaj: http://www.html5rocks.com/en/tutorials/file/filesystem/

 11
Author: Sparrow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-29 03:47:44

Provably you already try it, type "false"as following:

 rawFile.open("GET", file, false);
 11
Author: momen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-29 16:23:53

To może pomóc,

    var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            alert(xmlhttp.responseText);
        }
    }

    xmlhttp.open("GET", "sample.txt", true);
    xmlhttp.send();
 5
Author: Sameera R.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-18 15:20:44
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {            
                $.ajax({`enter code here`
                    url: "TextFile.txt",
                    dataType: "text",
                    success: function (data) {                 
                            var text = $('#newCheckText').val();
                            var str = data;
                            var str_array = str.split('\n');
                            for (var i = 0; i < str_array.length; i++) {
                                // Trim the excess whitespace.
                                str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
                                // Add additional code here, such as:
                                alert(str_array[i]);
                                $('#checkboxes').append('<input type="checkbox"  class="checkBoxClass" /> ' + str_array[i] + '<br />');
                            }
                    }                   
                });
                $("#ckbCheckAll").click(function () {
                    $(".checkBoxClass").prop('checked', $(this).prop('checked'));
                });
        });
    </script>
</head>
<body>
    <div id="checkboxes">
        <input type="checkbox" id="ckbCheckAll" class="checkBoxClass"/> Select All<br />        
    </div>
</body>
</html>
 1
Author: adithya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-22 07:41:25