How to read a local text file?

2018-12-31 00:58发布

I’m trying to write a simple text file reader by creating a function that takes in the file’s path and converts each line of text into a char array, but it’s not working.

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

What is going wrong here?

This still doesn’t seem to work after changing the code a little bit from a previous revision and now it’s giving me an XMLHttpRequest exception 101.

I’ve tested this on Firefox and it works, but in Google Chrome it just won’t work and it keeps giving me an Exception 101. How can I get this to work on not just Firefox, but also on other browsers (especially Chrome)?

11条回答
长期被迫恋爱
2楼-- · 2018-12-31 01:32

You need to check for status 0 (as when loading files locally with XMLHttpRequest, you don't get a status returned because it's not from a 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);
}

And specify file:// in your filename:

readTextFile("file:///C:/your/path/to/file.txt");
查看更多
素衣白纱
3楼-- · 2018-12-31 01:32

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>

查看更多
临风纵饮
4楼-- · 2018-12-31 01:36

Local AJAX calls in Chrome are not supported due to same-origin-policy.

If you check console logs you will find "Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https."

What this basically means that chrome creates a sort of virtual disk for every domain and access to files outside it are restricted by the listed methods for security reasons. AJAX is basically http, therefore wont work for local files.

Firefox does not put any such restriction therefore your code will work happily in firefox. However there is workaround for chrome too : see here.

查看更多
还给你的自由
5楼-- · 2018-12-31 01:39

Jon Perryman,

Yes js can read local files (see FileReader()) but not automatically: the user has to pass the file or a list of files to the script with an html <input type=file>.

Then with js it is possible to process (example view) the file or the list of files, some of their properties and the file or files content.

What js cannot do for security reasons is to access automatically (without the user input) to the filesystem of his computer.

To allow js to acccess to the local fs automatically is needed to create not an html file with js inside it but an hta document.

An hta file can contain js or vbs inside it.

But the hta executable will work on windows systems only.

This is standard browser behavior.

Also google chrome worked at the fs api, more infos here: http://www.html5rocks.com/en/tutorials/file/filesystem/

查看更多
无与为乐者.
6楼-- · 2018-12-31 01:40
<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>
查看更多
弹指情弦暗扣
7楼-- · 2018-12-31 01:41

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

 rawFile.open("GET", file, false);
查看更多
登录 后发表回答