0

How do I load a list of files from a specified folder in javascript?

update

Actually is from a Xul application, but I think anything for a local html file will work.. (it's a standalone app). And are resource files (images) I'm talking about..

x0n
  • 51,312
  • 7
  • 89
  • 111
The Student
  • 27,520
  • 68
  • 161
  • 264
  • 2
    Not enough details - in a browser? In windows scripting host? If in a browser, is it sandboxed? firefox XUL? etc etc. This is not a clear question. – x0n Sep 20 '10 at 19:56
  • See also: http://stackoverflow.com/questions/1087246/can-javascript-access-a-filesystem – Daniel Vandersluis Sep 20 '10 at 19:57
  • JavaScript can't access local resources as far as files and data go. You can give JavaScript a 64bit string that represents an image and JS can use that... but if you want javaScript to access the local disk, you better hope your users still use IE5 or IE6. – Ryan Ternier Sep 20 '10 at 21:49
  • @Ryan_Ternier I want javascript to access a resource image located in the same folder as the running js file. I have an "images/" folder that goes together with the js, and I want to load a list of image files of this folder. – The Student Sep 21 '10 at 11:46

3 Answers3

1

It's possible within a Firefox plug-in and has been for years. See the following page on MDC: https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO

Tim Down
  • 318,141
  • 75
  • 454
  • 536
1

If the folder is user-selected you can use the HTML5 File[1] APIs to read the files:

<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>

document.querySelector('#files').onchange = function(e) {
  var files = e.target.files; // FileList

  var output = [];
  for (var i = 0, f; f = files[i]; ++i) {
    output.push('<li><b>', f.name, '</b> (',
                f.type || 'n/a', ') - ', f.size, ' bytes</li>');
    // TODO: Use FileReader to actually read file.
  }
  document.querySelector('#list').innerHTML = '<ul>' + output.join('') + '</ul>';
};
ebidel
  • 23,921
  • 3
  • 63
  • 76
0

If you're talking about JS in a browser and accessing files on the client's machine, you can't. Javascript has no access to the filesystem for security reasons.

Daniel Vandersluis
  • 91,582
  • 23
  • 169
  • 153