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

Easiest way to get list of files in the server directory

本文关键字:列表 最简单 方法 文件 中文 服务器 获取      更新时间:2023-09-26

我需要在目录(例如www.example.com/images/)中获得所有图像(或简单的所有文件)的数组。我更喜欢使用JavaScript,但它很难制作。我应该用PHP吗?

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

非常感谢!

我不同意@mariobgr的回答。如果没有服务器设置阻止目录列表,那么通过请求该目录生成的html可以解析其内容。
$ tree maindir
maindir
├── index.html
└── somedir
    ├── doc1
    ├── doc2
    └── doc3

index . 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>

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

http://php.net/manual/en/function.glob.php就是你需要的。

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

我设法在基础javascript中使用修改后的ajax命令来获取文件夹列表作为html文件。然后我从里面提取文件名:

function loadDoc() {
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    
                    // gets the entire html file of the folder 'logpost' in this case and labels it thing
                    thing = this.responseText
                    searchFor = /.html</g
                    a=0;
                    b=0;
                    var str = "";
            
                    // greps file for .html and then backs up leter by letter till you hot the file name and all
                    while ((dothtmls = searchFor.exec(thing)) != null ){
                        str = "";
                        console.log(dothtmls.index);
                        
                        a = dothtmls.index;
                        while (thing[a]  != '>' ){
                            a--;
                        }
                        a++;
                        while(thing[a] != '<'){
                            str = str + thing[a];
                            a++;
                        }
                        console.log(str);
                    } 
                }
            };
            xhttp.open("GET", "logpost/", true);
            xhttp.send();
            }

这可能不是最干净的方式,但如果你是在一个静态的web服务器上工作,它应该工作:)