问题描述
有没有办法通过JavaScript选择目录?
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)
推荐答案
出于安全考虑,您不能(您不希望网站能够了解你的文件系统。)
You can't, for security reasons (you don't want a website to be able to know about your file system).
见下文,当你得到一个文件输入的值时,它会被破坏(在我的电脑上,例如它总是是 c:/ fakepath / something
)。文件输入也存在用例问题:选择一个文件夹会显示其内容列表,因此一个空文件夹将不会在我的代码段中记录任何内容。
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>
你可以做它通过插件,例如Flash,Java或Air,但用户必须已经安装或安装它。插件生态系统似乎已经死了。
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.
这篇关于在JavaScript中选择目录路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!