使用 Javascript 读取本地文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27522979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:16:05  来源:igfitidea点击:

Read a local text file using Javascript

javascripttext-files

提问by M. El-Set

I have read some of the previous questions on this topic but I really need to be 100% sure!

我已经阅读了之前关于这个主题的一些问题,但我真的需要 100% 确定!

Is it possible to read from a .txt file on my local system and present it in my HTML-BODY?

是否可以从本地系统上的 .txt 文件中读取并将其显示在我的 HTML-BODY 中?

I have tried several functions, here is one:

我尝试了几个功能,这里是一个:

  function readFile (path) {
  var fso = new ActiveXObject('Scripting.FileSystemObject'),
      iStream=fso.OpenTextFile(path, 1, false);
  while(!iStream.AtEndOfStream) {
      document.body.innerHTML += iStream.ReadLine() + '<br/>';
  }        
  iStream.Close();
}
readFile("testing.txt");

The content of the file is simply around 100 words I want to read from the text file and display in my HTML-BODY.

该文件的内容只有大约 100 个单词,我想从文本文件中读取并显示在我的 HTML-BODY 中。

Is this possible without having my own server?

如果没有我自己的服务器,这可能吗?

回答by Aminul

You can use a FileReaderobject to read text file here is example code:

您可以使用FileReader对象读取文本文件,这里是示例代码:

  <div id="page-wrapper">

        <h1>Text File Reader</h1>
        <div>
            Select a text file: 
            <input type="file" id="fileInput">
        </div>
        <pre id="fileDisplayArea"><pre>

    </div>
<script>
window.onload = function() {
        var fileInput = document.getElementById('fileInput');
        var fileDisplayArea = document.getElementById('fileDisplayArea');

        fileInput.addEventListener('change', function(e) {
            var file = fileInput.files[0];
            var textType = /text.*/;

            if (file.type.match(textType)) {
                var reader = new FileReader();

                reader.onload = function(e) {
                    fileDisplayArea.innerText = reader.result;
                }

                reader.readAsText(file);    
            } else {
                fileDisplayArea.innerText = "File not supported!"
            }
        });
}

</script>

Here is the codepen demo

这是codepen演示

If you have a fixed file to read every time your application load then you can use this code :

如果每次加载应用程序时都有一个固定文件要读取,则可以使用以下代码:

<script>
var fileDisplayArea = document.getElementById('fileDisplayArea');
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;
                fileDisplayArea.innerText = allText 
            }
        }
    }
    rawFile.send(null);
}

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

回答by RameshPasa

I think due to security concernit is not possible to read the file from local machine(Client side) without any client intervention.

我认为出于安全考虑,在没有任何客户端干预的情况下,不可能从本地机器(客户端)读取文件。

I have tried following code provided by Aminul

我尝试了以下Aminul提供的代码

<script>
var fileDisplayArea = document.getElementById('fileDisplayArea');
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;
                fileDisplayArea.innerText = allText 
            }
        }
    }
    rawFile.send(null);
}

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

it is giving access denied message as shown below enter image description here

它给出了访问被拒绝的消息,如下所示 在此处输入图片说明

回答by Karim

Please find below the code that generates automatically the content of the txt local file and display it html. Good luck!

请在下面找到自动生成txt本地文件内容并将其显示为html的代码。祝你好运!

<html>
<head>
  <meta charset="utf-8">
  <script type="text/javascript">

  var x;
  if(navigator.appName.search('Microsoft')>-1) { x = new ActiveXObject('MSXML2.XMLHTTP'); }
  else { x = new XMLHttpRequest(); }

  function getdata() {
    x.open('get', 'data1.txt', true); 
    x.onreadystatechange= showdata;
    x.send(null);
  }

  function showdata() {
    if(x.readyState==4) {
      var el = document.getElementById('content');
      el.innerHTML = x.responseText;
    }
  }

  </script>
</head>
<body onload="getdata();showdata();">

  <div id="content"></div>

</body>
</html>