HTML/Javascript:遍历本地(服务器端)文件夹的所有元素

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

HTML/Javascript: Iterate through all elements of local (server-side) folder

javascripthtmlfile-iodirectory

提问by ScoWalt

Basically, I have a very simple website where the root directory looks like:

基本上,我有一个非常简单的网站,其根目录如下所示:

/images/
index.html
stuff.js

I want some way to recursively iterate through every file in the /images/ directory and display them in order in a section of my website. So for example, if /images/ contained:

我想要某种方式递归遍历 /images/ 目录中的每个文件,并在我网站的某个部分按顺序显示它们。例如,如果 /images/ 包含:

images/a/a.png
images/b.png
images/c.jpg
....

then somewhere in index.html would contain:

那么 index.html 中的某处将包含:

<img src="images/a/a.png" />
<img src="images/b.png" />
<img src="images/c.jpg" />
....

My first idea was to do this using the document.write() function in stuff.js, but I couldn't find a good way to iterate through the local file directory in Javascript. I saw something about AJAX, but all of those examples involved editing an existing file, which I obviously don't want to do.

我的第一个想法是使用 stuff.js 中的 document.write() 函数来执行此操作,但是我找不到在 Javascript 中遍历本地文件目录的好方法。我看到了一些关于 AJAX 的内容,但所有这些示例都涉及编辑现有文件,我显然不想这样做。

My current solution is just to manual create an array of strings containing all of the files in /images/, but doing this makes me think "There's got to be a better way!"

我目前的解决方案只是手动创建一个包含 /images/ 中所有文件的字符串数组,但是这样做让我觉得“必须有更好的方法!”

Let me know if I've been unclear.

如果我不清楚,请告诉我。

Thanks!

谢谢!

回答by Jeffrey Sweeney

Perhaps the best way to do this is to use a server-sided language to do it for you, and to use an asynchronous Javascript request to display the data.

也许最好的方法是使用服务器端语言为您做这件事,并使用异步 Javascript 请求来显示数据。

This sample uses PHP to list all the files in a specified directory, and an xmlhttprequestto load this output and convert the results into image tags:

此示例使用 PHP 列出指定目录中的所有文件,并xmlhttprequest加载此输出并将结果转换为图像标签:



getimages.php:

getimages.php:

<?php

    //The directory (relative to this file) that holds the images
    $dir = "Images";


    //This array will hold all the image addresses
    $result = array();

    //Get all the files in the specified directory
    $files = scandir($dir);


    foreach($files as $file) {

        switch(ltrim(strstr($file, '.'), '.')) {

            //If the file is an image, add it to the array
            case "jpg": case "jpeg":case "png":case "gif":

                $result[] = $dir . "/" . $file;

        }
    }

    //Convert the array into JSON
    $resultJson = json_encode($result);

    //Output the JSON object
    //This is what the AJAX request will see
    echo($resultJson);

?>


index.html (same directory as getimages.php):

index.html(与 getimages.php 相同的目录):

<!DOCTYPE html>
<html>
    <head>
        <title>Image List Thing</title>
    </head>
    <body>

        <div id="images"></div>
        <input type="button" onclick="callForImages()" value="Load" />

        <script>

            //The div element that will contain the images
            var imageContainer = document.getElementById("images");



            //Makes an asynch request, loading the getimages.php file
            function callForImages() {

                //Create the request object
                var httpReq = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");

                //When it loads,
                httpReq.onload = function() {

                    //Convert the result back into JSON
                    var result = JSON.parse(httpReq.responseText);

                    //Show the images
                    loadImages(result);
                }

                //Request the page
                try {
                    httpReq.open("GET", "getimages.php", true);
                    httpReq.send(null);
                } catch(e) {
                    console.log(e);
                }

            }


            //Generates the images and sticks them in the container
            function loadImages(images) {

                //For each image,
                for(var i = 0; i < images.length; i++) {

                    //Make a new image element, setting the source to the source in the array
                    var newImage = document.createElement("img");
                    newImage.setAttribute("src", images[i]);

                    //Add it to the container
                    imageContainer.appendChild(newImage);

                }

            }

            </script>

    </body>
</html>

Note that this is only an example. You'll probably want to make sure that the AJAX call is successful, and that the JSON conversion works both in the server code and on the client.

请注意,这只是一个示例。您可能希望确保 AJAX 调用成功,并且 JSON 转换在服务器代码和客户端上都有效。

回答by Mike Gledhill

I stumbled on this article, as I was looking for the same thing, how to iterate through a list of files in a "Resources" folder, and display a webpage with clickable shortcuts to each of them.

我偶然发现了这篇文章,因为我正在寻找同样的东西,如何遍历“资源”文件夹中的文件列表,并显示一个网页,其中每个文件都有可点击的快捷方式。

Here's a clip of the webpage I ended up with:

这是我最终得到的网页片段:

enter image description here

在此处输入图片说明

Here's how I did it.

这是我如何做到的。

I added a very simple ASP.Net service, to iterate through the files in this folder...

我添加了一个非常简单的 ASP.Net 服务,以遍历此文件夹中的文件...

List<OneResourceFile> listOfFilenames = new List<OneResourceFile>();

string Icon = "";
string localFolder = Server.MapPath("../Resources");
string[] fileEntries = Directory.GetFiles(localFolder);
foreach (string fileName in fileEntries)
{
    string filename = System.IO.Path.GetFileName(fileName);
    switch (Path.GetExtension(filename).ToLower())
    {
        case ".pptx":
        case ".ppt":
            Icon = "cssPowerPoint";
            break;
        case ".doc":
        case ".docx":
            Icon = "cssWord";
            break;
        case ".xlsx":
        case ".xlsm":
        case ".xls":
            Icon = "cssExcel";
            break;
        default:
            Icon = "cssUnknown";
            break;
    }
    OneResourceFile oneFile = new OneResourceFile()
    {
        Filename = filename,
        IconClass = Icon,
        URL = "../Resources/" + filename
    };
    listOfFilenames.Add(oneFile);
}

string JSON = JsonConvert.SerializeObject(listOfFilenames);
return JSON;

..which built up a List of OneResouceFilerecords, each with a Filename, a CSS Class to apply to that shortcut (which would give it, say, an Excel icon, a PDF icon, etc) and a full URL of the item.

..它建立了一个OneResouceFile记录列表,每个记录都有一个文件名、一个应用于该快捷方式的 CSS 类(这会给它一个 Excel 图标、一个 PDF 图标等)和一个项目的完整 URL。

public class OneResourceFile
{
    public string Filename { get; set; }
    public string IconClass { get; set; }
    public string URL { get; set; }
}

..and which returned a JSON set of results like this...

..并且它返回了一组像这样的 JSON 结果......

[
    {
        Filename: "Mikes Presentation.pptx",
        IconClass: "cssPowerPoint",
        URL: "~/Resources/Mikes Presentation.pptx"
    },
    {
        Filename: "Mikes Accounts.xlsx",
        IconClass: "cssExcel",
        URL: "~/Resources/Mikes Accounts.xlsx""
    }
]

Then, I just got some JQuery to call this web service, and create a a hreffor each item in the results:

然后,我得到了一些 JQuery 来调用这个 Web 服务,并a href为结果中的每个项目创建一个:

<script type="text/javascript">
    var URL = "/GetListOfResourceFiles.aspx";   //  This is my web service
    $.ajax({
        url: URL,
        type: 'GET',
        cache: false,
        dataType: "json",
        success: function (JSON) {
            // We've successfully loaded our JSON data
            $.each(JSON.Results, function (inx) {

                // Create one <a href> per JSON record, and append it to our list.
                var thelink = $('<a>', {
                    text: this.Filename,
                    title: this.Filename,
                    href: this.URL,
                    class: this.IconClass
                }).appendTo('#ListOfResources');
            });
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert("$.ajax error: " + xhr.status + " " + thrownError);
        }  
    });
</script>

<p id="ListOfResources">

All you need then is to add some CSS styling for cssPowerPoint, cssExcel, etc, to give the a hrefs a relevant icon, for example:

所有你需要的则是添加一些CSS样式的cssPowerPointcssExcel等等,给予a hrefSA相关的图标,例如:

.cssPowerpoint
{
    vertical-align: top;
    text-align: center;
    background-repeat: no-repeat;
    background-position: center 5px;
    background-image: url(/Images/Icons/icnPowerPoint.png);
    width: 100px;
    height: 60px;
    padding-top: 60px;
    text-decoration: none;
    display:inline-block;
    color: #666;
    margin-left: 20px;
}

And that's it. Cool, hey ?

就是这样。酷,嘿?