Read more

HTML file inputs support picking directories

Arne Hartherz
August 14, 2018Software engineer at makandra GmbH

HTML's <input type="file"> accepts a single file. You can allow multiple files via <input type="file" multiple>.
But sometimes, selecting multiple files is not enough and can be cumbersome for the user. Enter webkitdirectory:

<input type="file" webkitdirectory multiple>
Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

Using webkitdirectory switches the browser's file picker to select a directory. All files inside that directory, and inside any nested subdirectories, will be selected for the file input.

This can be useful when users want to upload all files from a nested directory structure. Note that users could also add lots of files if they selected a root directory or similar.

Usage

Add webkitdirectory to your file input and you are good to go. Your event handler needs to handle event.target.files just like for a multiple input.

Note that file entries will have a webkitRelativePath property which lists the relative file path, starting from the selected directory (including it).

Example: http://jsfiddle.net/xozvprdj/ Show archive.org snapshot

Note that Chrome will show a confirmation prompt to make users aware that they selected a directory. Firefox and Edge won't.

Browser support

Although the property is called webkitdirectory and not directory, it is supported by Chrome, Firefox, Edge 14+, and Safari 11.1+.
Older browsers support multiple, so you should offer that as a fallback.

I've seen examples using directory but there are no indications this attribute will become standard soon. Feel free to use <input type="file" multiple webkitdirectory directory> to feel future-proof.

On JavaScript file objects, webkitRelativePath is supported similarly to webkitdirectory in HTML. As a fallback for older browsers you can use name (which won't include any path).

Posted by Arne Hartherz to makandra dev (2018-08-14 12:31)