createFileDialog

Category Browser

Creates a file dialog to interact with programatically.

Demo

Selected Files (0)

    Empty...

Usage

<script>
	import { createFileDialog } from '@sv-use/core';
 
	const dialog = createFileDialog();
</script>

Examples

<script>
	import { createFileDialog } from '@sv-use/core';
 
	const dialog = createFileDialog({
		accept: 'image/*',
		multiple: true,
		onChange(files) {
			console.log($state.snapshot(files));
		},
		onCancel() {
			console.log('cancelled');
		}
	});
</script>
 
<button onclick={dialog.open}>
    Open file dialog
</button>
<button
    onclick={dialog.reset}
    disabled={dialog.files.length === 0}
>
    Reset
</button>
<div class="flex flex-col gap-5">
    <span>Selected Files ({dialog.files.length})</span>
    {#if dialog.files}
        <ul>
            {#each dialog.files as file (file.name)}
                <li>{file.name}</li>
            {/each}
        </ul>
    {:else}
        <p>No files detected</p>
    {/if}
</div>
Type definitions
import type { CleanupFunction } from '../../__internal__/types.js';
type CreateFileDialogOptions = {
    /**
     * Whether to automatically clean up the event listeners or not.
     * @note If set to `true`, you must call `createFileDialog` in the component initialization lifecycle.
     * @default true
     */
    autoCleanup?: boolean;
    /** @default '*' */
    accept?: string;
    /** @default false */
    multiple?: boolean;
    /**
     * Triggers when the file selection changes.
     * @default () => {}
     */
    onChange?: (files: File[]) => void;
    /**
     * Triggers when the dialog is closed.
     * @default () => {}
     */
    onCancel?: () => void;
};
type CreateFileDialogReturn = {
    /**
     * A list of selected files.
     * @reactive
     */
    readonly files: File[];
    /** Opens the file dialog. */
    open: () => void;
    /** Resets the file dialog. */
    reset: () => void;
    /** Cleans up the input node and the event listeners. */
    cleanup: CleanupFunction;
};
/**
 * Creates a file dialog to interact with programatically.
 * @param options Additional options to customize the behavior.
 * @see https://svelte-librarian.github.io/sv-use/docs/core/browser/create-file-dialog
 */
export declare function createFileDialog(options?: CreateFileDialogOptions): CreateFileDialogReturn;
export {};

Sources