有没有办法只使用 Javascript 从文件夹中返回所有图像文件名的列表?

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

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

javascriptjquery

提问by Pooja

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 来计算文件夹中图像文件的数量?

回答by Euan

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.

IE

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

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

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:

2)然后用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"));
     });
  }
});

回答by Edizkan Adil Ata

This will list all jpgfiles in the folder you define under url: and append them to a divas a paragraph. Can do it with ul lias well.

这将列出jpg您在 url: 下定义的文件夹中的所有文件,并将它们div作为段落附加到 a中。也可以这样做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')

     });
  }
});

回答by James Allardice

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
});

回答by James Allardice

Although you can run FTP commands using WebSockets, the simpler solution is listing your files using opendirin 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),

    for example a file size,

  • 使用<a>标签来呈现链接。
  • 使用服务器端 ( PHP)查询更多信息,

    例如文件大小

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

PHP 文件大小提示  您还可以使用以下方法轻松克服PHP 文件大小2GB 限制:AJAX + HEAD 请求 + .htaccess 规则以允许Content-Length从客户端访问。

<?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>

回答by megaten

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")使用<a href='full/file/name' >Split文件名 的文本</a>

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

因此$(data).find("a:contains(.jpg)")无法检测到扩展名。

I hope this is useful

我希望这是有用的

回答by Thielicious

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.

恕我直言,Edizkan Adil Ata 的想法实际上是最恰当的方式。它提取锚标记的 URL 并将它们放在不同的标记中。如果您不想让页面访问者看到锚点,那么只需.hide()使用 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.

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