0

Is there a way, in Javascript, to get a list of files in a folder (on a server) that I can dynamically load into an array that I can work with when a page loads?

3
Contributors
17
Replies
20
Views
7 Years
Discussion Span
Last Post by ms_sws
0

Is there a way, in Javascript, to get a list of files in a folder (on a server)

If your server is configured to block directory access (most are), then no: you need to use server-side scripting.

In the unlikely event that it isn't so configured, then a qualified yes.

This

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <meta name="generator" content=
    "HTML Tidy for Windows (vers 25 March 2009), see www.w3.org">
    <title></title>
  </head>
  <body>
    <center>
      <form>
        <input type="button" value="Show"
        onclick="window.location.href=window.location.href.substring(0,1+window.location.href.lastIndexOf('/'))">
      </form>
    </center>
  </body>
</html>

is all it takes to test: it will either return a permission/access error page or a listing of the directory in which it is placed (except in your root directory, where it returns the default page [index.html or equivalent]).

Note: opening this page in Windows (by saving to the desktop, for example, and clicking) produces interesting [to me, anyway] browser-dependent output:
Opera - over-stylishly formatted page with clickable navigation
Firefox - neatly formatted page with clickable navigation
Chrome - crudely formatted page with clickable navigation (reminds me of ftp)
IE8 - an Explorer window [by default]
Safari(pc) - "You don’t have permission to open this page."

0

Okay so if I need to test this against a folder off the root directory? In other words, I need to run your test html page from the root directory but on a folder under the root directory?

When I place this inside the folder in question, I do get a directory listing. It does look a little like an FTP listing but inside an IE window. Oddly I get two Show buttons both clickable and producing the same results.

Anyway, how do I run this against a sub-folder?

(By the way, thanks fxm, I learn a lot from you!)

0

I need to run your test html page NOT from the root directory but on a folder under the root directory?

<emphasis added>

Yes. If you place it in your root directory, you won't get a directory; all you will get is your default page.

When I place this inside the folder in question, I do get a directory listing.

Amazing! The admin must have been asleep for the last decade or so.

Anyway, how do I run this against a sub-folder?

Manually, in 'toy' mode? Just navigate from whereever you installed it. Or move/copy the toy to the desired directory.

If you mean in javascript, you need to do the equivalent of setting the desired path in window.location.href (making sure that it ends with a "/").

I'm so surprised that it actually got a result that I haven't really given any thought to a version that demonstrates something useful.

Edited by fxm: n/a

0

Sorry, you lost me. What do I do to test this against a sub-folder off the root?

Then of course my very next question will be how do I get the results to load into an array using javascript.

0

What do I do to test this against a sub-folder off the root?

Install it in the desired sub-directory or sub-folder.

next question will be how do I get the results to load into an array using javascript

If you succeed at step 1 I can make some suggestions.

0

I did install it in the sub-folder and I do get a directory listing back from that sub-folder.

What I want, though, is to install it one folder up but get the directory listing from the sub-folder. And I want to be able to get the listing to load directly into an array so that I can work with it programmatically. And to do that, the logic in your test file has to be executed from the parent folder.

0

Changing the original code

onclick="window.location.href=window.location.href.substring(0,1+window.location.href.lastIndexOf('/'))"

to

onclick="window.location.href=window.location.href.substring(0,1+window.location.href.lastIndexOf('/'))+'subdirectory/'"

is all there is to it.

In most situations this

onclick="window.location.href='./subdirectory/'"

will work as well.

Notes:
be sure to match the case of ' ./subdirectory/ ' exactly to the name on the server
don't omit the trailing '/' (and in the second one don't miss the leading './'
' ./subdirectory/ ' may actually be a partial path
' ./subdirectory/sub/subsubdirectory/ ' [always ending with a '/']
depending on where you install the program in relation to what you want to access

0

Well I tried both versions of your onclick syntax. I have a subdirectory 'and' an html file both called gallery. The syntax:

onclick="window.location.href=window.location.href.substring(0,1+window.location.href.lastIndexOf('/'))+'gallery/'"

causes the gallery page to open when I click on the Show button while the syntax:

onclick="window.location.href='./gallery/'"

causes the home page to open.

??

0

OK, I looked at the file.
The first problem is that somehow you copied the code into the page multiple times, so there are two buttons - and one of them has two onclick= values.
The second is that you are using the example string 'subdirectory' in the command; you should have replaced that with the actual name of the directory you want to reach.

0

Wow. I really don't know how that happened. I obviously hit ctrl-v more than once then didn't notice what was strung on the end of that DOCTYPE tag. I'm embarrassed I didn't notice it. Anyway, 'now' I'm getting the correct folder directory listing from the sub-folder. So, now the next question is how do I get those results into an array?

0

Here is a demo.

This

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <meta name="generator" content=
    "HTML Tidy for Windows (vers 25 March 2009), see www.w3.org">
    <title></title>
    <script type="text/javascript">
/* Common functions */

    function getReq() {
    var oREQ = false;
        // ActiveX is used only for testing with IE8 on my XP desktop
    if (window.location.protocol == 'file:') {
        if (window.ActiveXObject) {
            try {
                oREQ = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                oREQ = false;
            }
        } else {
            if (window.XMLHttpRequest) {
                try {
                    oREQ = new XMLHttpRequest();
                } catch(e) {
                    oREQ = false;
                }
            }
        }

    } else {
        if (window.XMLHttpRequest) {
            try {
                oREQ = new XMLHttpRequest();
            } catch(e) {
                oREQ = false;
            }
        } else if (window.ActiveXObject) {
            try {
                oREQ = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                oREQ = false;
            }
        }
    }

    if (!oREQ) {
        alert("Your browser does not support XMLHttpRequest.");
        window.location.replace('main.html');
    }
    return oREQ;
    }


    function testURIsuccess(uri, pre_id) {
    var oREQ = getReq();

    var success = true;
    _error_msg = "";
    try {
        oREQ.open("GET", uri, false);
        oREQ.send("");
    } catch(e) {
        success = false;
        _error_msg = "Error: " + e;
    }

    if (oREQ.status != 0 && oREQ.status != 200 && oREQ.status != 304) {
        // don't want to catch caching problems here...
        success = false;
        _error_msg = "Status Code: " + oREQ.status;
    }

    if (oREQ.responseText.length == 0 ) {
        success = false
    }

//	alert(oREQ.responseText)

    var aFiles = oREQ.responseText.match(/[^"]+\.\S+(?=">)/g)
    var oTmp = document.getElementById('show')
    oTmp.innerHTML = aFiles //    alert(aFiles)

    }

    </script>
  </head>
  <body>
    <button onclick="testURIsuccess('./gallery','')">click</button>
    <pre id='show'>
</pre>
  </body>
</html>

is the toy web page and this

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
 <head>
  <title>Index of ..</title>
 </head>
 <body>
<h1>Index of ..</h1>
<ul><li><a href=".."> Parent Directory</a></li>
<li><a href="DM1.jpg"> DM1.jpg</a></li>

<li><a href="DM2.jpg"> DM2.jpg</a></li>
<li><a href="DM3.jpg"> DM3.jpg</a></li>
<li><a href="DM4.jpg"> DM4.jpg</a></li>
<li><a href="DM5.jpg"> DM5.jpg</a></li>
<li><a href="DM6.jpg"> DM6.jpg</a></li>
<li><a href="DM7.jpg"> DM7.jpg</a></li>

<li><a href="DM8.jpg"> DM8.jpg</a></li>
<li><a href="Missing_Photo.gif"> Missing_Photo.gif</a></li>
</ul>
</body></html>

is the toy directory.

To see it in action [copying the filenames to the aFiles array and displaying that], save both files to your desktop and open the webpage.

To test it on your site, change line 88 of the webpage to

<button onclick="testURIsuccess('./gallery/','')">click</button>

[the added "/" is critical], upload the page and open it.

If it doesn't display the filenames on the server the same way it does on the desktop, contact me by email.

0

It worked!!! Thank you SO much for all your help!!!! I'm still unclear why I was unable to test this from my local PC. My 'development environment' on my PC mirrors that of the server with respect to folders/file names yet the load of files inside my sub-folder just wouldn't load. No errors. It just seems as if window.location or window.XMLHttpRequest simply is not valid. Any ideas why? I had to test this by making changes then uploading the page to the server (not ideal when you want to ensure the page works 'before' you upload even though you can mitigate this issue with the inconvenience of renaming your page something else while you're testing).

0

When you say "worked", do you mean that you are using the filenames in the array on the server? If so, please mark this thread "solved" :)

As to the rest of it, access via XMLHttpRequest to folders on your PC is dependent on browser and security settings. On the site there may be a problem with older versions of IE (pre-7, think); if that is, in fact, happening, I can partially compensate.

0

I had to test this by making changes then uploading the page to the server

I usually drag the file to my desktop, edit with my favorite editor, then drag it back. If you're careful you can edit with SPD or FP.

That all assumes WebFolders. Otherwise (server permitting) you can do nearly the same with the ftp client built into the browser (IE) or added in (FireFTP+Firefox, or equivalent).

0

I use Coffeecup HTML Editor with file folders that mirror what's on the server. Coffeecup has an FTP function built in as well as a test in browser function. I am running XP and IE8. But when I test the html file from my PC those errors occur (whether I test within Coffeecup or test through my browser against the local html file). But everything works correctly once the same file is uploaded to the server and run there. So I can certainly work around the problem. I was just curious as to why the errors occur on my PC. I'll close this thread and if you have ideas, you have my e-mail address as well as the location of the gallery.html file that causes the problem locally.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.