File System Access API: Reading and Writing Local Files from WordPress Admin

Read and write local files from the WordPress admin with the File System Access API

An admin tool that imports a CSV or exports settings usually goes through the server: upload the file, parse it in PHP, offer a download. For files that only the browser needs to read or write, the File System Access API opens a native file dialog and gives the script a handle to the file. The user can even save changes back into the same file. It is a Chromium feature, so the tool needs a fallback that works everywhere.

Problem: A plugin’s settings page has “Export settings” and “Import settings” buttons. The export creates a JSON file on the server for download, the import uploads it, and both go through a temporary folder in uploads that is never cleaned up.

Solution: Read the import file in the browser with showOpenFilePicker() (fallback: <input type="file">), validate it and send only the settings JSON to the REST API. For the export, write the JSON with showSaveFilePicker() (fallback: a download link with a Blob URL). No file ever touches the server.

Import: open a file

// js/settings-transfer.js
async function haPickJsonFile() {
    if ( 'showOpenFilePicker' in window ) {
        const [ handle ] = await window.showOpenFilePicker( {
            types: [ { description: 'Settings', accept: { 'application/json': [ '.json' ] } } ],
            multiple: false,
        } );
        return handle.getFile();
    }
    // fallback for Firefox and Safari
    return new Promise( ( resolve, reject ) => {
        const input = Object.assign( document.createElement( 'input' ), { type: 'file', accept: '.json,application/json' } );
        input.addEventListener( 'change', () => ( input.files[ 0 ] ? resolve( input.files[ 0 ] ) : reject( new Error( 'No file' ) ) ) );
        input.click();
    } );
}

document.querySelector( '#ha-import' ).addEventListener( 'click', async () => {
    try {
        const file = await haPickJsonFile();
        if ( file.size > 1024 * 1024 ) throw new Error( 'The file is larger than 1 MB.' );
        const settings = JSON.parse( await file.text() );

        const response = await fetch( window.haTransfer.endpoint, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': window.haTransfer.nonce },
            body: JSON.stringify( settings ),
        } );
        if ( ! response.ok ) throw new Error( ( await response.json() ).message );
        location.reload();
    } catch ( error ) {
        if ( error.name !== 'AbortError' ) alert( error.message ); // AbortError = dialog cancelled
    }
} );

Both ways return a File object, so the rest of the code is the same. file.text() reads it as a string. The settings still go to the server for saving, and the REST endpoint must validate and sanitize every value as if it came from a form, because a JSON file can contain anything.

Export: save a file

async function haSaveJson( data, suggestedName ) {
    const blob = new Blob( [ JSON.stringify( data, null, 2 ) ], { type: 'application/json' } );

    if ( 'showSaveFilePicker' in window ) {
        const handle = await window.showSaveFilePicker( {
            suggestedName,
            types: [ { description: 'Settings', accept: { 'application/json': [ '.json' ] } } ],
        } );
        const writable = await handle.createWritable();
        await writable.write( blob );
        await writable.close();
        return;
    }

    const url = URL.createObjectURL( blob );
    const link = Object.assign( document.createElement( 'a' ), { href: url, download: suggestedName } );
    link.click();
    setTimeout( () => URL.revokeObjectURL( url ), 1000 );
}

document.querySelector( '#ha-export' ).addEventListener( 'click', () => {
    haSaveJson( window.haTransfer.settings, 'ha-settings.json' ).catch( ( error ) => {
        if ( error.name !== 'AbortError' ) alert( error.message );
    } );
} );

With the picker, the user chooses folder and name in a native dialog. The data is written to a temporary file and moved into place on close(), so a crash halfway does not leave a broken file. The fallback downloads the file into the default download folder.

The PHP side

add_action( 'rest_api_init', function (): void {
    register_rest_route( 'ha/v1', '/settings', array(
        'methods'             => 'POST',
        'permission_callback' => fn() => current_user_can( 'manage_options' ),
        'callback'            => function ( WP_REST_Request $request ) {
            $input = (array) $request->get_json_params();
            update_option( 'ha_settings', array(
                'color'   => sanitize_hex_color( $input['color'] ?? '' ) ?: '#2271b1',
                'limit'   => min( 100, absint( $input['limit'] ?? 10 ) ),
                'enabled' => ! empty( $input['enabled'] ),
            ) );
            return array( 'saved' => true );
        },
    ) );
} );

Only known keys are taken over, each with its own sanitizing function. Endpoints like this: custom REST API endpoints with authentication and schema validation.

Rules of the API

  • The pickers open only in reaction to a user action (a click) and only on HTTPS pages (or localhost).
  • The script gets access only to the file or folder the user picked, never to the file system as a whole.
  • File handles can be stored in IndexedDB to write to the same file later; the browser asks again for permission in a new session.

NOTE: showOpenFilePicker() and showSaveFilePicker() work in Chrome and Edge since version 86 (2020). Firefox and Safari have decided not to implement the pickers, so the fallbacks are not optional: they are what many users get. Both browsers support the Origin Private File System part of the API (navigator.storage.getDirectory()), which is a sandboxed storage for the site and does not give access to the user’s files.