Javascript 获取服务器目录中文件列表的最简单方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30622369/
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 05:28:51  来源:igfitidea点击:

Easiest way to get list of files in the server directory

javascriptphpimageserver

提问by Jan Chalupa

I need to get array of all images (or simply of all files) in directory (e.g. www.example.com/images/). I prefer to use JavaScript but it's hard to make. So should I use PHP, meybe?

我需要在目录(例如 www.example.com/images/)中获取所有图像(或只是所有文件)的数组。我更喜欢使用 JavaScript,但很难做到。那么我应该使用PHP吗?

Could you please help me - I'm not good at this.

你能帮帮我吗 - 我不擅长这个。

Thank you very much!

非常感谢!

采纳答案by mariobgr

Javascript cannot fetch all files on a server, as it is a client-side langugage.

Javascript 无法获取服务器上的所有文件,因为它是一种客户端语言。

http://php.net/manual/en/function.glob.phpis what you need.

http://php.net/manual/en/function.glob.php正是您所需要的。

$all = glob('/path/to/dir/*.*');

$images = glob('/path/to/dir/*.{jpg,png,gif}');

回答by abalter

I disagree with @mariobgr. If there is no server setting preventing a directory listing, then the html generated by requesting that directory can be parsed for the contents.

我不同意@mariobgr。如果没有阻止目录列表的服务器设置,则可以解析通过请求该目录生成的 html 的内容。

$ tree maindir
maindir
├── index.html
└── somedir
    ├── doc1
    ├── doc2
    └── doc3

index.html

索引.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible"><!--  JQUERY  -->

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
  </script>
  <title></title>
</head>
<body>
  <h1>Listing /somedir</h1><!-- Custom Script (defered load, after dom ready) -->
  <script>
    $.getJSON('./somedir', data => {
        console.log(data); //["doc1.jpg", "doc2.jpg", "doc3.jpg"] 
    });
  </script>
</body>