简体   繁体   English

如何将文本文件导入javascript?

[英]How to import text file to javascript?

I'm kind of stuck on a problem, I'm trying to import a text file from my local computer to JavaScript and populate HTML dropdown's according to the text file. 我有点陷入困境,我正尝试将本地计算机中的文本文件导入JavaScript并根据文本文件填充HTML下拉列表。 I have spent a lot of time looking at similar questions on stack overflow and i haven't found the solution to the problem yet. 我已经花了很多时间在栈溢出上研究类似的问题,但是我还没有找到解决问题的方法。 Here is an example of what the text file looks like: 这是文本文件的示例:

     Dogs - 
     Blue Dog
     Black Doggo
     Random Doggo

     Cats -
     Neon cat
     Grumpy cat
     Potato cat

Here is what my js looks like: 这是我的js的样子:

     <html>
   <body>
<select name="myselect">
 </select>
  </body>
   <script>
  Function GetTxt() {
  var AllData = '';
  var StuffFile = new XMLHttpRequest();

  StuffFile.open("GET", "C:Users/Documents/Desktop/WeirdDoggos.txt",true)
   StuffFile.onreadystatechange = function(){
   if(StuffFile.readyStatus === 4) {
   if (StuffFile.status === 200 || StuffFile.status === 0) {
      AllData = StuffFile.responseText;
      var lines = StuffFile.responseText.split('/n').map(function (line){
      return line.trim   
   });
   var select = $("select[name=myselect]")
   var optionCounter = 0;
   var currentGroup = "";
   lines.forEach(function(line){
     if(line.endsWith(" -")){
  currentGroup = line.substring(0, line.length - 2);
   optionCounter = 0;
               select.append("<optgroup id='" + currentGroup + "' label='" + currentGroup + "'>")
   } else if(line === ""){
   select.append("</optgroup>");
   } else {
   select.append("<option type='checkbox' id='" 
      + (currentGroup + optionCounter) + "' name='" 
      + (currentGroup + optionCounter) + "' value='" 
      + line + "'>" + line + "</option>");
           }
       });
     }
    }
   }
   }
   </script>
   </html>

So I'm trying to populate Select name=”MySelect” in HTML, but I don't think it's importing the text file, any tips? 因此,我试图在HTML中填充Select name =“ MySelect”,但我不认为它正在导入文本文件,有什么提示吗?

You cannot read a file on a user's disk like that. 您无法像这样读取用户磁盘上的文件。 As @Puddingfox mentioned, it would be a huge security hole. 正如@Puddingfox提到的那样,这将是一个巨大的安全漏洞。 But what you can do is have a file input on the page where a user can select a text file on their computer and then read the contents of that file. 但是您可以做的是在页面上输入文件,用户可以在计算机上选择一个文本文件,然后读取该文件的内容。

The difference between these two is that with a file upload button, the user's explicit action is required for the website to read a file on their disk as opposed to just reading someone's files without them knowing or permitting it. 两者之间的区别在于,使用文件上传按钮,网站需要用户采取明确的行动才能读取其磁盘上的文件,而不是在用户不知道或不允许的情况下仅读取某人的文件。

Brian Campbell has a really good explanation of how to read the file after the user has selected it using the File API and I recommend reading what he had to say to learn a bit more about it. 在用户使用File API选择文件后, Brian Campbell对如何读取文件有很好的解释 ,我建议阅读他所说的内容,以了解更多信息。

A code sample of this is below. 下面的代码示例。

<html>

<body>
  <input type="file" id="file" />
  <script type="text/javascript">
    document.getElementById('file').onchange = () => {
      const file = document.getElementById('file').files[0];
      if (file) {
        const reader = new FileReader();
        reader.readAsText(file, 'UTF-8');
        reader.onload = (evt) => {
          console.log(evt.target.result);
          // Do stuff with the text data here...
        };
        reader.onerror = (evt) => {
          console.error('Failed to read this file');
        };
      }
    };
  </script>
</body>

</html>

Hope this points you in the right direction, at least. 希望这至少能为您指明正确的方向。

加上这个

StuffFile.open("GET", file:///User/**YOURUSERNAME**/Documents/Desktop/WeirdDoggos.txt ,true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM