是否有一种方法可以只使用Javascript从文件夹返回所有图像文件名的列表?

时间:2021-10-27 00:30:53

I want to display all images from folder located in server in image gallery.

我想要显示所有的图像,从位于图像库中的服务器文件夹。

Is there a way to return a list of all the image file names from a folder using only JavaScript or JQuery?

是否有一种方法可以只使用JavaScript或JQuery从文件夹返回所有图像文件名的列表?

Also I want to count the number of image files in similar folder using only JavaScript.

我还想只使用JavaScript计算类似文件夹中图像文件的数量。

Is there any way to count the number of image files from a folder using only JavaScript?

是否有办法只使用JavaScript从文件夹中计算图像文件的数量?

6 个解决方案

#1


31  

No, you can't do this using Javascript alone. Client-side Javascript cannot read the contents of a directory the way I think you're asking about.

不,你不能只使用Javascript。客户端Javascript不能像我认为的那样读取目录的内容。

However, if you're able to add an index page to (or configure your web server to show an index page for) the images directory and you're serving the Javascript from the same server then you could make an AJAX call to fetch the index and then parse it.

但是,如果您能够向映像目录添加索引页(或配置web服务器以显示索引页),并且您正在为来自同一服务器的Javascript提供服务,那么您可以进行AJAX调用来获取索引,然后对其进行解析。

i.e.

即。

1) Enable indexes in Apache for the relevant directory on yoursite.com:

1)为yoursite.com上的相关目录启用Apache中的索引:

http://www.cyberciti.biz/faq/enabling-apache-file-directory-indexing/

http://www.cyberciti.biz/faq/enabling-apache-file-directory-indexing/

2) Then fetch / parse it with jQuery. You'll have to work out how best to scrape the page and there's almost certainly a more efficient way of fetching the entire list, but an example:

然后用jQuery获取/解析它。你必须找到最好的抓取页面的方法,而且几乎可以肯定有一种更有效的方法来获取整个列表,但是举个例子:

$.ajax({
  url: "http://yoursite.com/images/",
  success: function(data){
     $(data).find("td > a").each(function(){
        // will loop through 
        alert("Found a file: " + $(this).attr("href"));
     });
  }
});

#2


23  

This will list all jpg files in the folder you define under url: and append them to a div as a paragraph. Can do it with ul li as well.

这将列出在url:下定义的文件夹中的所有jpg文件,并将它们附加到div中作为段落。也可以和ul li一起做。

$.ajax({
  url: "YOUR FOLDER",
  success: function(data){
     $(data).find("a:contains(.jpg)").each(function(){
        // will loop through 
        var images = $(this).attr("href");

        $('<p></p>').html(images).appendTo('a div of your choice')

     });
  }
});

#3


7  

No. JavaScript is a client-side technology and cannot do anything on the server. You could however use AJAX to call a server-side script (e.g. PHP) which could return the information you need.

不。JavaScript是客户端技术,不能在服务器上做任何事情。但是,您可以使用AJAX调用服务器端脚本(例如PHP),它可以返回您需要的信息。

If you want to use AJAX, the easiest way will be to utilise jQuery:

如果你想使用AJAX,最简单的方法就是使用jQuery:

$.post("someScript.php", function(data) {
   console.log(data); //"data" contains whatever someScript.php returned
});

#4


3  

Although you can run FTP commands using WebSockets, the simpler solution is listing your files using opendir in server side (PHP), and "spitting" it into the HTML source-code, so it will be available to client side.

尽管您可以使用WebSockets运行FTP命令,更简单的解决方案是使用opendir在服务器端(PHP)列出您的文件,并将其“吐入”到HTML源代码中,这样客户端就可以使用它了。

The following code will do just that,

下面的代码将会这样做,

Optionally -

可选地,

  • use <a> tag to present a link.
  • 使用标签来显示一个链接。
  • query for more information using server side (PHP),

    查询更多信息使用服务器端(PHP),

    for example a file size,

    例如文件大小,

PHP filesize TIP:   also you can easily overcome the 2GB limit of PHP's filesize using: AJAX + HEAD request + .htaccess rule to allow Content-Length access from client-side.

PHP filesize提示:还可以使用AJAX + HEAD request + .htaccess规则轻松克服PHP filesize的2GB限制,允许从客户端访问内容长度。

  • A Fully Working example can be found at my github repository: download.eladkarako.com

    可以在我的github存储库中找到一个完整的示例:download.eladkarako.com

  • The following is a trimmed-down (simplified) example:

    下面是一个简化的例子:

<?php
  /* taken from: https://github.com/eladkarako/download.eladkarako.com */

  $path = 'resources';
  $files = [];
  $handle = @opendir('./' . $path . '/');

  while ($file = @readdir($handle)) 
    ("." !== $file && ".." !== $file) && array_push($files, $file);
  @closedir($handle);
  sort($files); //uksort($files, "strnatcasecmp");

  $files = json_encode($files);

  unset($handle,$ext,$file,$path);
?>
<!DOCTYPE html>
<html lang="en-US" dir="ltr">
<head>
  <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
  <div data-container></div>
  <script>
    /* you will see (for example): 'var files = ["1.bat","1.exe","1.txt"];' if your folder containes those 1.bat 1.exe 1.txt files, it will be sorted too! :) */

    var files = <?php echo $files; ?>;

    files = files.map(function(file){
      return '<a data-ext="##EXT##" download="##FILE##" href="http://download.eladkarako.com/resources/##FILE##">##FILE##</a>'
        .replace(/##FILE##/g,       file)
        .replace(/##EXT##/g,        file.split('.').slice(-1) )
        ;
    }).join("\n<br/>\n");

    document.querySelector('[data-container]').innerHTML = files;
  </script>

</body>
</html>

DOM result will look like that:

DOM结果如下所示:

<html lang="en-US" dir="ltr"><head>
  <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
  <div data-container="">
    <a data-ext="bat" download="1.bat" href="http://download.eladkarako.com/resources/1.bat">1.bat</a>
    <br/>
    <a data-ext="exe" download="1.exe" href="http://download.eladkarako.com/resources/1.exe">1.exe</a>
    <br/>
    <a data-ext="txt" download="1.txt" href="http://download.eladkarako.com/resources/1.txt">1.txt</a>
    <br/>
  </div>
  <script>
    var files = ["1.bat","1.exe","1.txt"];

    files = files.map(function(file){
      return '<a data-ext="##EXT##" download="##FILE##" href="http://download.eladkarako.com/resources/##FILE##">##FILE##</a>'
        .replace(/##FILE##/g,       file)
        .replace(/##EXT##/g,        file.split('.').slice(-1) )
        ;
    }).join("\n<br/>\n");

    document.querySelector('[data-container').innerHTML = files;
  </script>


</body></html>

#5


0  

Many tricks work, but the Ajax request split the file name at 19 characters? Look at the output of the ajax request to see that:

有很多技巧可以使用,但是Ajax请求将文件名分割为19个字符?查看ajax请求的输出,可以看到:

The file name is okay to go into the href attribute, but the $(this).attr("href") use the text of the <a href='full/file/name' > Split file name </a>

文件名可以进入href属性,但是$(this).attr(“href”)使用 Split file name 的文本

So the $(data).find("a:contains(.jpg)") is not able to detect the extension.

因此,$(data).find(“a:contains(.jpg)”)不能检测扩展。

I hope this is useful

我希望这是有用的

#6


0  

IMHO, Edizkan Adil Ata's idea is actually the most proper way. It extracts the URLs of anchor tags and puts them in a different tag. And if you don't want to let the anchors being seen by the page visitor then just .hide() them all with JQuery or display: none; in CSS.

伊姆西坎·阿迪勒·阿塔的想法实际上是最合适的方式。它提取锚标记的url并将它们放在不同的标记中。如果不想让页面访问者看到锚点,那么就用JQuery或display: none隐藏();在CSS。

Also you can perform prefetching, like this:

你也可以进行预取,比如:

<link rel="prefetch" href="imagefolder/clouds.jpg" />

That way you don't have to hide it and still can extract the path to the image.

这样,您就不必隐藏它,仍然可以提取到映像的路径。

#1


31  

No, you can't do this using Javascript alone. Client-side Javascript cannot read the contents of a directory the way I think you're asking about.

不,你不能只使用Javascript。客户端Javascript不能像我认为的那样读取目录的内容。

However, if you're able to add an index page to (or configure your web server to show an index page for) the images directory and you're serving the Javascript from the same server then you could make an AJAX call to fetch the index and then parse it.

但是,如果您能够向映像目录添加索引页(或配置web服务器以显示索引页),并且您正在为来自同一服务器的Javascript提供服务,那么您可以进行AJAX调用来获取索引,然后对其进行解析。

i.e.

即。

1) Enable indexes in Apache for the relevant directory on yoursite.com:

1)为yoursite.com上的相关目录启用Apache中的索引:

http://www.cyberciti.biz/faq/enabling-apache-file-directory-indexing/

http://www.cyberciti.biz/faq/enabling-apache-file-directory-indexing/

2) Then fetch / parse it with jQuery. You'll have to work out how best to scrape the page and there's almost certainly a more efficient way of fetching the entire list, but an example:

然后用jQuery获取/解析它。你必须找到最好的抓取页面的方法,而且几乎可以肯定有一种更有效的方法来获取整个列表,但是举个例子:

$.ajax({
  url: "http://yoursite.com/images/",
  success: function(data){
     $(data).find("td > a").each(function(){
        // will loop through 
        alert("Found a file: " + $(this).attr("href"));
     });
  }
});

#2


23  

This will list all jpg files in the folder you define under url: and append them to a div as a paragraph. Can do it with ul li as well.

这将列出在url:下定义的文件夹中的所有jpg文件,并将它们附加到div中作为段落。也可以和ul li一起做。

$.ajax({
  url: "YOUR FOLDER",
  success: function(data){
     $(data).find("a:contains(.jpg)").each(function(){
        // will loop through 
        var images = $(this).attr("href");

        $('<p></p>').html(images).appendTo('a div of your choice')

     });
  }
});

#3


7  

No. JavaScript is a client-side technology and cannot do anything on the server. You could however use AJAX to call a server-side script (e.g. PHP) which could return the information you need.

不。JavaScript是客户端技术,不能在服务器上做任何事情。但是,您可以使用AJAX调用服务器端脚本(例如PHP),它可以返回您需要的信息。

If you want to use AJAX, the easiest way will be to utilise jQuery:

如果你想使用AJAX,最简单的方法就是使用jQuery:

$.post("someScript.php", function(data) {
   console.log(data); //"data" contains whatever someScript.php returned
});

#4


3  

Although you can run FTP commands using WebSockets, the simpler solution is listing your files using opendir in server side (PHP), and "spitting" it into the HTML source-code, so it will be available to client side.

尽管您可以使用WebSockets运行FTP命令,更简单的解决方案是使用opendir在服务器端(PHP)列出您的文件,并将其“吐入”到HTML源代码中,这样客户端就可以使用它了。

The following code will do just that,

下面的代码将会这样做,

Optionally -

可选地,

  • use <a> tag to present a link.
  • 使用标签来显示一个链接。
  • query for more information using server side (PHP),

    查询更多信息使用服务器端(PHP),

    for example a file size,

    例如文件大小,

PHP filesize TIP:   also you can easily overcome the 2GB limit of PHP's filesize using: AJAX + HEAD request + .htaccess rule to allow Content-Length access from client-side.

PHP filesize提示:还可以使用AJAX + HEAD request + .htaccess规则轻松克服PHP filesize的2GB限制,允许从客户端访问内容长度。

  • A Fully Working example can be found at my github repository: download.eladkarako.com

    可以在我的github存储库中找到一个完整的示例:download.eladkarako.com

  • The following is a trimmed-down (simplified) example:

    下面是一个简化的例子:

<?php
  /* taken from: https://github.com/eladkarako/download.eladkarako.com */

  $path = 'resources';
  $files = [];
  $handle = @opendir('./' . $path . '/');

  while ($file = @readdir($handle)) 
    ("." !== $file && ".." !== $file) && array_push($files, $file);
  @closedir($handle);
  sort($files); //uksort($files, "strnatcasecmp");

  $files = json_encode($files);

  unset($handle,$ext,$file,$path);
?>
<!DOCTYPE html>
<html lang="en-US" dir="ltr">
<head>
  <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
  <div data-container></div>
  <script>
    /* you will see (for example): 'var files = ["1.bat","1.exe","1.txt"];' if your folder containes those 1.bat 1.exe 1.txt files, it will be sorted too! :) */

    var files = <?php echo $files; ?>;

    files = files.map(function(file){
      return '<a data-ext="##EXT##" download="##FILE##" href="http://download.eladkarako.com/resources/##FILE##">##FILE##</a>'
        .replace(/##FILE##/g,       file)
        .replace(/##EXT##/g,        file.split('.').slice(-1) )
        ;
    }).join("\n<br/>\n");

    document.querySelector('[data-container]').innerHTML = files;
  </script>

</body>
</html>

DOM result will look like that:

DOM结果如下所示:

<html lang="en-US" dir="ltr"><head>
  <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
  <div data-container="">
    <a data-ext="bat" download="1.bat" href="http://download.eladkarako.com/resources/1.bat">1.bat</a>
    <br/>
    <a data-ext="exe" download="1.exe" href="http://download.eladkarako.com/resources/1.exe">1.exe</a>
    <br/>
    <a data-ext="txt" download="1.txt" href="http://download.eladkarako.com/resources/1.txt">1.txt</a>
    <br/>
  </div>
  <script>
    var files = ["1.bat","1.exe","1.txt"];

    files = files.map(function(file){
      return '<a data-ext="##EXT##" download="##FILE##" href="http://download.eladkarako.com/resources/##FILE##">##FILE##</a>'
        .replace(/##FILE##/g,       file)
        .replace(/##EXT##/g,        file.split('.').slice(-1) )
        ;
    }).join("\n<br/>\n");

    document.querySelector('[data-container').innerHTML = files;
  </script>


</body></html>

#5


0  

Many tricks work, but the Ajax request split the file name at 19 characters? Look at the output of the ajax request to see that:

有很多技巧可以使用,但是Ajax请求将文件名分割为19个字符?查看ajax请求的输出,可以看到:

The file name is okay to go into the href attribute, but the $(this).attr("href") use the text of the <a href='full/file/name' > Split file name </a>

文件名可以进入href属性,但是$(this).attr(“href”)使用 Split file name 的文本

So the $(data).find("a:contains(.jpg)") is not able to detect the extension.

因此,$(data).find(“a:contains(.jpg)”)不能检测扩展。

I hope this is useful

我希望这是有用的

#6


0  

IMHO, Edizkan Adil Ata's idea is actually the most proper way. It extracts the URLs of anchor tags and puts them in a different tag. And if you don't want to let the anchors being seen by the page visitor then just .hide() them all with JQuery or display: none; in CSS.

伊姆西坎·阿迪勒·阿塔的想法实际上是最合适的方式。它提取锚标记的url并将它们放在不同的标记中。如果不想让页面访问者看到锚点,那么就用JQuery或display: none隐藏();在CSS。

Also you can perform prefetching, like this:

你也可以进行预取,比如:

<link rel="prefetch" href="imagefolder/clouds.jpg" />

That way you don't have to hide it and still can extract the path to the image.

这样,您就不必隐藏它,仍然可以提取到映像的路径。