如何从 HTML 输入类型“文件”或任何其他方式得到文件夹目录?

所以我有一个类型 "file"的基本表单输入,但我希望用户能够选择一个文件夹位置,而不是一个文件。

我怎样才能让这个输入选择一个文件夹而不是一个文件,或者有其他方法来做到这一点?

162595 次浏览

You're most likely looking at using a flash/silverlight/activeX control. The <input type="file" /> control doesn't handle that.

If you don't mind the user selecting a file as a means to getting its directory, you may be able to bind to that control's change event then strip the filename portion and save the path somewhere--but that's about as good as it gets.

Keep in mind that webpages are designed to interact with servers. Nothing about providing a local directory to a remote server is "typical" (a server can't access it so why ask for it?); however files are a means to selectively passing information.

Stumbled on this page as well, and then found out this is possible with just javascript (no plugins like ActiveX or Flash)

Basically, they added support for a new attribute on the file input element "webkitdirectory". You can use it like this:

<input type="file" id="ctrl" webkitdirectory directory multiple/>

It allows you to select directories. The multiple attribute is a good fallback for browsers that support multiple file selection but not directory selection.

When you select a directory the files are available through the dom object for the control (document.getElementById('ctrl')), just like they are with the multiple attribute. The browsers adds all files in the selected directory to that list recursively.

You can already add the directory attribute as well in case this gets standardized at some point (couldn't find any info regarding that)

Eventhough it is an old question, this may help someone.

We can choose multiple files while browsing for a file using "multiple"

<input type="file" name="datafile" size="40"  multiple>

Update 2022:

You can do it now: https://developer.mozilla.org/en-US/docs/Web/API/Window/showDirectoryPicker

async function getDir() {
const dirHandle = await window.showDirectoryPicker();


// run code for dirHandle
}