Подтвердить что ты не робот

Как читать локальный текстовый файл?

Я пытаюсь написать простой текстовый файл, создавая функцию, которая принимает путь к файлам и преобразует каждую строку текста в массив char, но не работает.

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();
}

Что здесь происходит?

Это, похоже, не работает после изменения кода немного из предыдущей версии, и теперь это дает мне исключение XMLHttpRequest 101.

Ive проверил это на Firefox, и он работает, но в Google Chrome он просто не работает, и он продолжает давать мне Exception 101. Как я могу заставить это работать не только с Firefox, но и с другими браузерами (особенно с Chrome)

4b9b3361

Ответ 1

Вам нужно проверить статус 0 (как при загрузке файлов локально с помощью XMLHttpRequest, вы не получите статус, возвращенный, потому что он не от 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);
}

И укажите file:// в имени вашего файла:

readTextFile("file:///C:/your/path/to/file.txt");

Ответ 2

Посетите Javascripture! И перейдите в раздел readAsText и попробуйте пример. Вы сможете узнать, как работает функция readAsText 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>

Ответ 3

После введения fetch api в javascript чтение содержимого файла не может быть проще.

чтение текстового файла

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

чтение файла JSON

fetch('file.json')
  .then(response => response.json())
  .then(jsonResponse => console.log(jsonResponse))     
   // outputs a javascript object from the parsed json

Обновление 30/07/2018 (отказ от ответственности):

Этот метод отлично работает в Firefox, но кажется, что реализация fetch Chrome не поддерживает схему URL file:/// на момент написания этого обновления (протестировано в Chrome 68).

Ответ 4

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>

Ответ 5

Джон Перриман,

Да js может читать локальные файлы (см. FileReader()), но не автоматически: пользователь должен передать файл или список файлов в script с помощью html <input type=file>.

Затем с помощью js можно обрабатывать (пример) файл или список файлов, некоторые их свойства и содержимое файла или файлов.

Что не может сделать js по соображениям безопасности - это автоматически (без ввода пользователя) обращаться к файловой системе своего компьютера.

Чтобы разрешить js для доступа к локальным fs автоматически, необходимо создать не файл html с js внутри него, а hta-документ.

Файл hta может содержать js или vbs внутри него.

Но исполняемый файл hta будет работать только на системах Windows.

Это стандартное поведение браузера.

Также google chrome работал на fs api, здесь больше информации: http://www.html5rocks.com/en/tutorials/file/filesystem/

Ответ 6

Если вы уже попробовали, введите "false" следующим образом:

 rawFile.open("GET", file, false);

Ответ 7

Попробуйте создать две функции:

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]);
}

Ответ 8

другой пример - мой читатель с классом 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>

Ответ 9

Это может помочь,

    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();

Ответ 10

Использование Fetch и асинхронной функции

const logFileText = async file => {
    const response = await fetch(file)
    const text = await response.text()
    console.log(text)
}

logFileText('file.txt')

Ответ 11

Добавив к некоторым ответам выше, это модифицированное решение работало для меня.

<input id="file-upload-input" type="file" class="form-control" accept="*" />

....

let fileInput  = document.getElementById('file-upload-input');
let files = fileInput.files;

//Use createObjectURL, this should address any CORS issues.
let filePath = URL.createObjectURL(files[0]);

....

function readTextFile(filePath){
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", filePath , true);
    rawFile.send(null);

    rawFile.onreadystatechange = function (){
        if(rawFile.readyState === 4){
            if(rawFile.status === 200 || rawFile.status == 0){
                var allText = rawFile.responseText;
                console.log(allText);
            }
        }
    }     
}

Ответ 12

<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>

Ответ 13

Локальные вызовы AJAX в Chrome не поддерживаются из-за политики одного источника.

Если вы проверите журналы консоли, то увидите, что " Cross origin requests are not supported for protocol schemes: http, data, chrome, chrome-extension, https. ".

Это означает, что Chrome создает своего рода виртуальный диск для каждого домена, файлы, обслуживаемые доменом по перечисленным выше протоколам, хранятся на этом диске, доступ к файлам вне его на локальном диске ограничен в соответствии с той же политикой происхождения. AJAX-запросы и ответы происходят по http/https, поэтому не будут работать для локальных файлов.

Firefox не налагает такого ограничения, поэтому ваш код будет хорошо работать на Firefox. Однако есть и обходные пути для Chrome: см. Здесь.

Ответ 14

function readTextFile(file) {
    var rawFile = new XMLHttpRequest(); // XMLHttpRequest (often abbreviated as XHR) is a browser object accessible in JavaScript that provides data in XML, JSON, but also HTML format, or even a simple text using HTTP requests.
    rawFile.open("GET", file, false); // open with method GET the file with the link file ,  false (synchronous)
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4) // readyState = 4: request finished and response is ready
        {
            if(rawFile.status === 200) // status 200: "OK"
            {
                var allText = rawFile.responseText; //  Returns the response data as a string
                console.log(allText); // display text on the console
            }
        }
    }
    rawFile.send(null); //Sends the request to the server Used for GET requests with param null
}

readTextFile("text.txt"); //<= Call function ===== don't need "file:///..." just the path 

- прочитать текст файла из JavaScript
- Консольный журнал из файла с использованием JavaScript
- Google Chrome и Mozilla Firefox

в моем случае у меня есть такая структура файлов: enter image description here

результат console.log:
enter image description here

Ответ 15

Вы можете импортировать мою библиотеку:

<script src="https://www.editeyusercontent.com/preview/1c_hhRGD3bhwOtWwfBD8QofW9rD3T1kbe/[email protected]"></script>

Ответ 16

Чтобы читать текст локального файла через JavaScript с помощью chrome, браузер chrome должен запускаться с аргументом --allow-file-access-from-files чтобы разрешить JavaScript доступ к локальному файлу, затем вы можете прочитать его с помощью XmlHttpRequest как XmlHttpRequest ниже:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
   if (xmlhttp.readyState == 4) {
       var allText = xmlhttp.responseText;          
            }
        };
xmlhttp.open("GET", file, false);
xmlhttp.send(null);

Ответ 17

Получить данные локального файла в js (data.js) load:

function loadMyFile(){
    console.log("ut:"+unixTimeSec());
    loadScript("data.js?"+unixTimeSec(), loadParse);
}
function loadParse(){
    var mA_=mSdata.split("\n");
    console.log(mA_.length);
}
function loadScript(url, callback){

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}
function hereDoc(f) {
  return f.toString().
      replace(/^[^\/]+\/\*![^\r\n]*[\r\n]*/, "").
      replace(/[\r\n][^\r\n]*\*\/[^\/]+$/, "");
}
function unixTimeSec(){
    return Math.round( (new Date()).getTime()/1000);
}

Файл data.js похож на:

var mSdata = hereDoc(function() {/*!
17,399
1237,399
BLAHBLAH
BLAHBLAH
155,82
194,376
*/});

динамическое unixTime queryString предотвращает кэширование.

AJ работает в сети http://.

Ответ 18

Как прочитать локальный файл?

Используя это, вы загрузите файл с помощью loadText(), а затем JS будет асинхронно ждать, пока файл не будет прочитан и загружен, после чего он откроет функцию readText(), позволяющую вам продолжить работу с обычной логикой JS (вы также можете написать попытку try). блокировать функцию loadText() в случае возникновения какой-либо ошибки), но для этого примера я оставляю ее минимальной.

async function loadText(url) {
    text = await fetch(url);
    //awaits for text.text() prop 
    //and then sends it to readText()
    readText(await text.text());
}

function readText(text){
    //here you can continue with your JS normal logic
    console.log(text);
}

loadText('test.txt');