Search code examples
javascriptinternet-explorer-11file-handlinghtml5-filesystem

How can I have a user select a folder (not a file) on their local machine using javascript?


I have a web-based app from which I need to be able to pop up a File Open dialog box and have the user select a folder, the path for which is then populated into an HTML form field so that the user doesn't have to type it.

No files or folders are uploaded, just the path information.

The client platform/environment is Windows 7 with Internet Explorer 11, or optionally Safari on OS X (recent versions.) And it cannot use Java, Flash, or any other plugin which must be downloaded and installed - only what is installed by default on those platforms, such as ActiveX on windows.

I found this code which almost does what I need - but I can't figure out how to allow it to select a folder rather than just a non-folder file:

<html>
    <head>
    <script type="text/javascript" language="JavaScript">
    if (typeof String.prototype.startsWith != 'function') {
      // see below for better implementation!
      String.prototype.startsWith = function (str){
        return this.indexOf(str) == 0;
      };
    }

    function getUNCPath() {
        var fileName = document.getElementById("uploadedFile").value;

        var WshNetwork = new ActiveXObject("WScript.Network");
        var Drives = WshNetwork.EnumNetworkDrives();
        for (i = 0; i < Drives.length; i += 2) {
            if (fileName.startsWith(Drives.Item(i))) {
                var fullPath = fileName.replace(Drives.Item(i), Drives.Item(i + 1));
                alert(fullPath);
                break;
            }
        }
    }
    </script>
    </head>
    <body>
        <form onsubmit="getUNCPath()">
            <input type="file" id="uploadedFile"/>
            <input type="submit" value="Get the UNC Path!" />
        </form>
        <span id="uncPath"></span>
    </body>
</html>

I'm assuming that I need to use the File API, but my Google-fu fails me at finding a way to retrieve a folder name alone via the File API.


Solution

  • For security reasons you cannot do this, some browsers will even go as giving you fake directory information. Browsers won't allow you to access and explore the file system of the client computers using javascript.

    The File API verifies this

    The name of the file; on getting, this must return the name of the file as a string. There are numerous file name variations on different systems; this is merely the name of the file, without path information. On getting, if user agents cannot make this information available, they must return the empty string.