【问题标题】:JavaScript - Reading URLs from a file and saving them as elements in an arrayJavaScript - 从文件中读取 URL 并将它们保存为数组中的元素
【发布时间】:2016-02-12 20:07:32
【问题描述】:

我的 JavaScript 技能很少,我想将文件的行作为字符串参数传递给预先编写的函数。基本上我想要做的是以这种格式读取一个文件,每个 url 在它自己的行上:

www.url1.com www.url2.com

...等等

如何读取本地文件并将每一行保存到字符串数组?

非常感谢,如果有不清楚的地方请告诉我

【问题讨论】:

  • 请提供您迄今为止尝试过的内容。一个工作小提琴将是最好的。到目前为止,您还没有展示任何解决问题的尝试。
  • 另外,您是在尝试通过 FileReader “读入”文件,还是作为对 AJAX 请求的响应? aka,是本地文件还是远程文件?

标签: javascript arrays string file filereader


【解决方案1】:

您可以通过查看FileListFileFileReader Web API 来做到这一点。请注意,您的浏览器可能不支持这些 API,但大多数现代浏览器应该支持。您可以通过在 window 对象中查找它们的属性来检查它们是否存在。

我在下面添加了带有 cmets 的示例代码。

HTML:

<input id="f" type="file">

JavaScript:

// This event listener is triggered when you open a file with the input button.
document.getElementById('f').addEventListener('change', function(event) {
  // Get File from FileList.
  // Documentation: https://developer.mozilla.org/en-US/docs/Web/API/FileList
  var f = this.files[0]; // event.target.files[0] works too

  // Need an instance of this API for asynchronous file I/O.
  var fr = new FileReader();

  // First create a function to handle the "onload" event.
  fr.onload = function(event) {
    // FileReader.result holds file contents
    // Documentation: https://developer.mozilla.org/en-US/docs/Web/API/FileReader/result
    var textInFile = this.result; // event.target.result works too
    // String.prototype.split with newline character argument
    var urls = textInFile.split('\n');
    console.log(urls);
  }

  // This performs asynchronous I/O and eventually triggers the "onload" event.
  // Default encoding is UTF-8.
  // Documentation: https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsText
  fr.readAsText(f);
});

【讨论】:

    【解决方案2】:

    查看 HTML5 文件 API。

    有关示例,请参阅此博客文章:http://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api

    虽然有限制,但必须通过

    <input type="file">
    

    因此,您不能在用户不知情的情况下读取任意文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-09
      • 1970-01-01
      • 1970-01-01
      • 2015-02-20
      • 2014-02-28
      • 1970-01-01
      • 2021-04-04
      • 1970-01-01
      相关资源
      最近更新 更多