How to Use showOpenFilePicker in JavaScript

The showOpenFilePicker() method is a core feature of the File System Access API that allows web applications to prompt users to select files from their local device and read their contents directly within JavaScript. Unlike traditional <input type="file"> elements, this modern API provides direct, programmatic access to file handles, offering greater control over file types, multi-file selection, and seamless interaction with the local file system.

How the Method Works

Calling window.showOpenFilePicker() displays a native operating system file picker dialog. Because accessing local files is a sensitive action, this method must be triggered by a direct user interaction, such as a button click, and requires a secure context (HTTPS).

When the user selects a file, the method resolves a Promise that returns an array of FileSystemFileHandle objects. Each handle represents a selected file and provides methods to access the file’s data and metadata.

Basic Implementation

To read data from a selected file, you request the file handle, retrieve the standard File object using getFile(), and then extract the content using standard read methods like text(), arrayBuffer(), or stream().

async function openLocalFile() {
  try {
    // 1. Open the native file picker
    const [fileHandle] = await window.showOpenFilePicker();

    // 2. Get the File object from the handle
    const file = await fileHandle.getFile();

    // 3. Read the file contents
    const contents = await file.text();

    console.log(`File Name: ${file.name}`);
    console.log(`File Content:`, contents);
  } catch (error) {
    if (error.name !== 'AbortError') {
      console.error('File selection failed:', error);
    }
  }
}

If the user cancels the file picker prompt, the Promise rejects with an AbortError, allowing applications to handle cancellations gracefully.

Configuring Picker Options

The showOpenFilePicker() method accepts an optional configuration object to customize the selection criteria:

const pickerOptions = {
  multiple: false,
  excludeAcceptAllOption: true,
  types: [
    {
      description: 'Text and Markdown Documents',
      accept: {
        'text/plain': ['.txt'],
        'text/markdown': ['.md']
      }
    }
  ]
};

const [fileHandle] = await window.showOpenFilePicker(pickerOptions);

Key Advantages Over Traditional File Inputs

  1. Persistent References: The returned FileSystemFileHandle can be stored in IndexedDB, allowing web applications to retain a reference to the file across sessions without re-prompting the user immediately.
  2. Writable Access: With appropriate permissions, the same handle can be used to write data back to the original local file via fileHandle.createWritable().
  3. Cleaner Syntax: The Promise-based API fits naturally into modern asynchronous JavaScript patterns without needing to attach event listeners to hidden DOM elements.