Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to read files from a directory using javascript?

I want to read a directory and fill a list with the name of those files.

Is it possible to do this tasks using javascript?

like image 455
aF. Avatar asked Oct 19 '25 05:10

aF.


2 Answers

No, for security reasons.

You might be able to do it by invoking ActiveX or Flash and having the user agree to permit file system access from these plugins, but - please don't.

Edit 10 years on: Not only please don't do this, but now outside of using an old device without updates - you can't do this with Flash/ActiveX.

like image 70
Widor Avatar answered Oct 21 '25 18:10

Widor


It's 2022, a lot of changes in the world and beyond, and, lo and behold, now we have something called File System Access API:

This API allows interaction with files on a user's local device, or on a user-accessible network file system. Core functionality of this API includes reading files, writing or saving files, and access to directory structure.

It became available in Chrome 86 (released in October 2020). Safari added support in 15.2 version, released in the end of 2021. To the moment of writing this, Firefox doesn't support this feature though (here's the related discussion).

Also, security considerations didn't go anywhere:

This API opens up potential functionality the web has been lacking. Still, security has been of utmost concern when designing the API, and access to file/directory data is disallowed unless the user specifically permits it.


This part is no longer relevant (kudos to @gignu for mentioning that in the comments) and is left here for historical reasons.

I suppose the closest you might get by using webkitdirectory attribute:

HTML

<input type="file" id="file_input" webkitdirectory="" directory="" />
<div id="list_of_files"></div>
...

JS

var $list = $('#list_of_files');
$('#file_input').change(function(event) {
  var listOfFiles = event.target.files;
  for (var i = 0, l = listOfFiles.length; i < l; ++i) {
     $list.append($('<p>'+ listOfFiles[i].name +'</p>'));
  }
});

... as shown here. But it works in Chrome only (and suggested usage of mozdirectory attribute didn't help).

like image 24
raina77ow Avatar answered Oct 21 '25 19:10

raina77ow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!