5

Is there any way to select a directory via JavaScript?

Not for uploading a file, just to choose a directory path. (Directory dialog or something)

das-g
  • 9,718
  • 4
  • 38
  • 80
David
  • 239
  • 1
  • 2
  • 12

2 Answers2

2

You can't, for security reasons (you don't want a website to be able to know about your file system).

See below, when you get the value of a file input, it will be mangled (on my computer, for example it will always be c:/fakepath/something). The file input also has problems for your usecase : selecting a folder will give you the list of its contents, so an empty folder will log nothing in my snippet.

function browseResult(e){
  var fileselector = document.getElementById('fileselector');
  console.log(fileselector.value);
}
<input id="fileselector" type="file" onchange="browseResult(event)" webkitdirectory directory multiple="false" style="display:none" />
<button onclick="getElementById('fileselector').click()">browse</button>

You could do it via a plugin, such as Flash, Java or Air for example, but users would have to either have it installed already or install it. The plugin ecosystem seems pretty much dead.

Boris
  • 1,161
  • 9
  • 20
  • 2
    Thanks. I don't want my app to choose a file. Just to choose in some way a folder path, not a file – David Jun 22 '17 at 14:43
  • I understand but I don't think it is possible. Not in javascript, anyway. You could have them type the path in a textfield, but that's not as convenient. – Boris Jun 22 '17 at 14:45
-1

you cannot get path directly, best you find online to reach to path:

$('#fileUploadControl').on('change',function ()
        {
            var filePath = $(this).val();
            console.log(filePath);
        });

It will give you blank in Firefox and 'Fakepath/..' in chrome. (Not have tested in IE but of course won't help you.)

Tejas Vaishnav
  • 492
  • 2
  • 14
  • 1
    Thanks. I don't want my app to choose a file. Just to choose in some way a folder path, not a file. – David Jun 22 '17 at 14:43