【问题标题】:How to read files in directory in Javascript如何在Javascript中读取目录中的文件
【发布时间】:2018-01-15 11:18:23
【问题描述】:

我现在必须从给定目录中读取文件名作为 URL 例如。

http://somesite.whereisthis/directoryThatContainsFiles

我想过 XMLHttpRequest 之类的

xhr.open('GET', 'http://somesite.whereisthis/directoryThatContainsFiles', true);

然后以某种方式读取此文件夹中的文件名,但我无法使其工作:/

如何在纯 javascript 中阅读它们?(没有 jquery 或其他东西)有没有办法在 console.log(); 中列出它?

【问题讨论】:

标签: javascript directory xmlhttprequest


【解决方案1】:

您对“Javascript”的期望很高

如果没有服务器端的帮助,您将无法做到这一点。例如,您可以使用 PHP 将目录列表数据作为 JSON 响应发送。

http://hostaddress/endpointdirectory

  {
      "Folder" : "Data"
      "Files"  : [ "File1" , "File2" ]
  }

否则,使用 XMLHttpRequest() 可以解决简单的 hack,您将获得 HTML DOM 响应。

 <html>
 <head>
 <title>Index of /directoryWantToList</title>
 </head>
  <body>
 <h1>Index of /directoryWantToList</h1>
 <table>
 <tr><th valign="top"><img src="/icons/blank.gif" alt="[ICO]"></th><th><a 
  href="?C=N;O=D">Name</a></th><th><a href="?C=M;O=A">Last modified</a></th>
  <th><a href="?C=S;O=A">Size</a></th><th><a href="?C=D;O=A">Description</a>
  </th></tr>
  <tr><th colspan="5"><hr></th></tr>
  <tr><td valign="top"><img src="/icons/back.gif" alt="[PARENTDIR]"></td>
  <td><a href="/">Parent Directory</a>       </td><td>&nbsp;</td><td 
   align="right">  - </td><td>&nbsp;</td></tr>
  <tr><td valign="top"><img src="/icons/text.gif" alt="[TXT]"></td><td><a 
  href="File1.txt">File1.txt</a>              </td><td align="right">2018-
  01-15 16:52  </td><td align="right">  0 </td><td>&nbsp;</td></tr>
  <tr><td valign="top"><img src="/icons/text.gif" alt="[TXT]"></td><td><a 
  href="File2.txt">File2.txt</a>              </td><td align="right">2018-
  01-15 16:52  </td><td align="right">  0 </td><td>&nbsp;</td></tr>
  <tr><th colspan="5"><hr></th></tr>
  </table>
  <address>Apache/2.4.29 (Win32) OpenSSL/1.1.0g PHP/7.2.0 Server at 
  localhost Port 80</address>
  </body></html>

使用此 DOM 响应,您需要通过解析元素来获取这些文件名,这是一个糟糕的 hack.....

如今,Javascript 发展了很多,但仍仅限于客户端。

参考线程:

  1. Listing files of a directory in a webpage

  2. get a list of all folders in directory

【讨论】:

    猜你喜欢
    • 2013-10-19
    • 2013-02-03
    • 1970-01-01
    • 2019-09-15
    • 2015-07-10
    • 1970-01-01
    • 2011-08-26
    • 2012-04-09
    • 2010-10-18
    相关资源
    最近更新 更多