ScoWalt
ScoWalt

Reputation: 421

How can I iterate through all elements of local (server-side) folder?

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/a/a.png
images/b.png
images/c.jpg
....

then somewhere in index.html would contain:

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

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!"

Let me know if I've been unclear.

Thanks!

Upvotes: 6

Views: 18558

Answers (2)

Mike Gledhill
Mike Gledhill

Reputation: 29191

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

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 OneResouceFile records, 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.

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

[
    {
        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 href for each item in the results:

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

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

Upvotes: 1

Jeffrey Sweeney
Jeffrey Sweeney

Reputation: 6124

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.

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


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):

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

Upvotes: 8

Related Questions