Explain Codes LogoExplain Codes Logo

Directory Chooser in HTML page

html
directory-chooser
security-restrictions
user-experience
Anton ShumikhinbyAnton Shumikhin·Feb 5, 2025
TLDR

Instantly add a directory chooser in HTML via an <input> element. Just set type="file" and throw in the webkitdirectory attribute. Prompt users to pick directories, simplifying folder uploads.

<input type="file" webkitdirectory>

Remember, this strategy's success depends on browser compatibility and user permissions aplenty.

For universal usage, lean on the File System Access API's showDirectoryPicker() method, because it launches a directory picker dialog, no sweat.

async function chooseDirectory() { try { // Hello Mr. Handle, nice to meet you! const dirHandle = await window.showDirectoryPicker(); // Behold, the directory handle is ready to work! } catch (e) { console.error(e); // Oopsie daisy! Handle errors. Don't be a fool, stay in school! } } // Go ahead, trigger the directory selection through user events like button clicks.

Thanks to this API, you’re offering users a seamless and smooth directory selection experience. It’s like taking a walk in the park!

Deep dive into webkitdirectory and security

The webkitdirectory attribute makes your life easier. However, security restrictions dictate its operation:

  • The attribute provides relative path info of the chosen directory, never exposing full paths — it values privacy!
  • Unwanted access to user files is a big no-no. Privacy shield mode engaged!

Elevate user experience with directory choosers

With a keen eye for good UX, your directory chooser is on its way to stardom:

  • Put a snazzy label on the <input> button to express its action.
  • Serve up guidelines or subtle UI hints that gently guide users through the selection process.
  • Offer a virtual high-five (maybe in the form of a success message) after a directory is successfully selected!

Playing nice: Compatibility across browsers

Make peace with the fact that different browsers and versions require different handshakes:

  • webkitdirectory isn’t a universal best friend. Check compatibility on Can I Use to ensure it'll fit right with your audience's browsers.
  • The File System Access API is the new kid on the block, not yet universally accepted. Keep fallbacks ready!

When client-side isn’t enough: Server-side alternatives

Sometimes, you need to go server-side to fully control directory selection:

  • Java-based apps can use JFileChooser. Here's a jar of Java code for you:
JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); chooser.setAcceptAllFileFilterUsed(false); // With this, you’re saying no to everything but directories. It’s good to be picky sometimes!
  • Trigger server-side selection using the browser, then process the result.
  • While powerful, these methods might make your users work a little harder. It’s like going for a jog instead of a walk!