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

时间:2015-06-03 14:01:17

标签: javascript php image server

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

你可以帮助我 - 我不擅长这个。

非常感谢!

3 个答案:

答案 0 :(得分:4)

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

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

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

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

答案 1 :(得分:2)

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

if(($(this).closest('#glaceblock').length || $(this).closest('#sorbetblock').length) && $(this).find('.deleteSorbGlaceItem').length ===0){

的index.html

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

访问<!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> $.get('http://localhost/maindir/somedir', (data) => { console.log(data); let listing = parseDirectoryListing(data); $('body').append(JSON.stringify(listing)); }); function parseDirectoryListing(text) { let docs = text .match(/href="([\w]+)/g) // pull out the hrefs .map((x) => x.replace('href="', '')); // clean up console.log(docs); return docs; } </script> </body> 会产生:

  

列表/ somedir
  [ “DOC1”, “DOC2”, “doc3的”]

答案 2 :(得分:1)

我设法使用修改后的ajax命令在基本javascript中做到这一点,以将文件夹作为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();
            }

这可能不是清洁方法,但是如果您使用的是静态网络服务器,则应该可以使用:)