[英]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. 我有一个基于Web的应用程序,需要从其中弹出一个“文件打开”对话框,让用户选择一个文件夹,然后将其路径填充到HTML表单字段中,以使用户不必键入。
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. 客户端平台/环境是带有Internet Explorer 11的Windows 7,或者是OS X(最新版本)上的Safari(可选)。它不能使用Java,Flash或任何其他必须下载并安装的插件-仅默认安装在这些平台,例如Windows上的ActiveX。
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. 我以为我需要使用File API,但是我的Google-fu无法让我找到一种通过File API单独检索文件夹名称的方法。
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. 浏览器不允许您使用javascript访问和浏览客户端计算机的文件系统。
The File API verifies this File API对此进行验证
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. 获取时,如果用户代理无法提供此信息,则必须返回空字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.