Skip to content

FilePicker

Examples#

Live example

Pick, save, and get directory paths#

import flet as ft


def main(page: ft.Page):
    page.services.append(file_picker := ft.FilePicker())

    async def handle_pick_files(e: ft.Event[ft.Button]):
        files = await file_picker.pick_files_async(allow_multiple=True)
        selected_files.value = (
            ", ".join(map(lambda f: f.name, files)) if files else "Cancelled!"
        )

    async def handle_save_file(e: ft.Event[ft.Button]):
        save_file_path.value = await file_picker.save_file_async()

    async def handle_get_directory_path(e: ft.Event[ft.Button]):
        directory_path.value = await file_picker.get_directory_path_async()

    page.add(
        ft.Row(
            controls=[
                ft.Button(
                    content="Pick files",
                    icon=ft.Icons.UPLOAD_FILE,
                    on_click=handle_pick_files,
                ),
                selected_files := ft.Text(),
            ]
        ),
        ft.Row(
            controls=[
                ft.Button(
                    content="Save file",
                    icon=ft.Icons.SAVE,
                    on_click=handle_save_file,
                    disabled=page.web,  # disable this button on web
                ),
                save_file_path := ft.Text(),
            ]
        ),
        ft.Row(
            controls=[
                ft.Button(
                    content="Open directory",
                    icon=ft.Icons.FOLDER_OPEN,
                    on_click=handle_get_directory_path,
                    disabled=page.web,  # disable this button on web
                ),
                directory_path := ft.Text(),
            ]
        ),
    )


ft.run(main)

pick-save-and-get-directory-path

Pick and upload files#

import flet as ft

state = {"picked_files": []}


def main(page: ft.Page):
    prog_bars: dict[str, ft.ProgressRing] = {}

    def on_upload_progress(e: ft.FilePickerUploadEvent):
        prog_bars[e.file_name].value = e.progress

    # add to services
    page.services.append(file_picker := ft.FilePicker(on_upload=on_upload_progress))

    async def handle_files_pick(e: ft.Event[ft.ElevatedButton]):
        files = await file_picker.pick_files_async(allow_multiple=True)
        print("Picked files:", files)
        state["picked_files"] = files

        # update progress bars
        upload_button.disabled = len(files) == 0
        prog_bars.clear()
        upload_progress.controls.clear()
        for f in files:
            prog = ft.ProgressRing(value=0, bgcolor="#eeeeee", width=20, height=20)
            prog_bars[f.name] = prog
            upload_progress.controls.append(ft.Row([prog, ft.Text(f.name)]))

    async def handle_file_upload(e: ft.Event[ft.ElevatedButton]):
        upload_button.disabled = True
        file_picker.upload(
            files=[
                ft.FilePickerUploadFile(
                    name=file.name,
                    upload_url=page.get_upload_url(f"dir/{file.name}", 60),
                )
                for file in state["picked_files"]
            ]
        )

    page.add(
        ft.Text("test"),
        ft.ElevatedButton(
            content="Select files...",
            icon=ft.Icons.FOLDER_OPEN,
            on_click=handle_files_pick,
        ),
        upload_progress := ft.Column(),
        upload_button := ft.ElevatedButton(
            content="Upload",
            icon=ft.Icons.UPLOAD,
            on_click=handle_file_upload,
            disabled=True,
        ),
    )


ft.run(main, upload_dir="examples")

pick-and-upload

FilePicker #

Bases: Service

A control that allows you to use the native file explorer to pick single or multiple files, with extensions filtering support and upload.

Important

In Linux, the FilePicker control depends on Zenity when running Flet as an app. This is not a requirement when running Flet in a browser.

To install Zenity on Ubuntu/Debian run the following commands:

sudo apt-get install zenity

data #

data: Any = skip_field()

Arbitrary data of any type.

key #

key: (
    str | int | float | bool | ValueKey | ScrollKey | None
) = None

on_upload #

on_upload: EventHandler[FilePickerUploadEvent] | None = None

Called when a file upload progress is updated.

page #

page: Page | PageView | None

The page (of type Page or PageView) to which this control belongs to.

parent #

parent: BaseControl | None

The direct ancestor(parent) of this control.

It defaults to None and will only have a value when this control is mounted (added to the page tree).

The Page control (which is the root of the tree) is an exception - it always has parent=None.

before_event #

before_event(e: ControlEvent)

before_update #

before_update()

This method is called every time when this control is being updated.

Note

Make sure not to call/request an update() here.

did_mount #

did_mount()

get_directory_path_async #

get_directory_path_async(
    dialog_title: str | None = None,
    initial_directory: str | None = None,
) -> str | None

Selects a directory and returns its absolute path.

PARAMETER DESCRIPTION
dialog_title

The title of the dialog window. Defaults to [`FilePicker.

TYPE: str | None DEFAULT: None

initial_directory

The initial directory where the dialog should open.

TYPE: str | None DEFAULT: None

init #

init()

is_isolated #

is_isolated()

pick_files_async #

pick_files_async(
    dialog_title: str | None = None,
    initial_directory: str | None = None,
    file_type: FilePickerFileType = ANY,
    allowed_extensions: list[str] | None = None,
    allow_multiple: bool = False,
) -> list[FilePickerFile]

Retrieves the file(s) from the underlying platform.

PARAMETER DESCRIPTION
dialog_title

The title of the dialog window.

TYPE: str | None DEFAULT: None

initial_directory

The initial directory where the dialog should open.

TYPE: str | None DEFAULT: None

file_type

The file types allowed to be selected.

TYPE: FilePickerFileType DEFAULT: ANY

allow_multiple

Allow the selection of multiple files at once.

TYPE: bool DEFAULT: False

allowed_extensions

The allowed file extensions. Has effect only if file_type is FilePickerFileType.CUSTOM.

TYPE: list[str] | None DEFAULT: None

save_file_async #

save_file_async(
    dialog_title: str | None = None,
    file_name: str | None = None,
    initial_directory: str | None = None,
    file_type: FilePickerFileType = ANY,
    allowed_extensions: list[str] | None = None,
    src_bytes: bytes | None = None,
) -> str | None

Opens a save file dialog which lets the user select a file path and a file name to save a file.

PARAMETER DESCRIPTION
dialog_title

The title of the dialog window.

TYPE: str | None DEFAULT: None

file_name

The default file name.

TYPE: str | None DEFAULT: None

initial_directory

The initial directory where the dialog should open.

TYPE: str | None DEFAULT: None

file_type

The file types allowed to be selected.

TYPE: FilePickerFileType DEFAULT: ANY

src_bytes

TBA

TYPE: bytes | None DEFAULT: None

allowed_extensions

The allowed file extensions. Has effect only if file_type is FilePickerFileType.CUSTOM.

TYPE: list[str] | None DEFAULT: None

Note
  • This method only opens a dialog for the user to select a location and file name, and returns the chosen path. The file itself is not created or saved.
  • This method is only available on desktop platforms (Linux, macOS & Windows).
Saving a file on web

To save a file from the web, you actually don't need to use a FilePicker.

You can instead provide an API endpoint /download/:filename that returns the file content, and then use page.launch_url to open the url, which will trigger the browser's save file dialog.

Take FastAPI as an example, you can use the following code to implement the endpoint:

from fastapi import FastAPI, Response
from fastapi.responses import FileResponse

app = flet_fastapi.app(main)

@app.get("/download/{filename}")
def download(filename: str):
    path = prepare_file(filename)
    return FileResponse(path)

and then use page.launch_url("/download/myfile.txt") to open the url, for instance, when a button is clicked.

ft.ElevatedButton(
    "Download myfile",
    on_click=lambda _: page.launch_url("/download/myfile.txt"),
)

update #

update() -> None

upload #

upload(files: list[FilePickerUploadFile])

Uploads selected files to specified upload URLs.

Before calling this method, pick_files_async() must be called, so that the internal file picker selection is not empty.

PARAMETER DESCRIPTION
files

A list of FilePickerUploadFile, where each item specifies which file to upload, and where (with PUT or POST).

TYPE: list[FilePickerUploadFile]

upload_async #

upload_async(files: list[FilePickerUploadFile])

Uploads selected files to specified upload URLs.

Before calling this method, pick_files_async() must be called, so that the internal file picker selection is not empty.

PARAMETER DESCRIPTION
files

A list of FilePickerUploadFile, where each item specifies which file to upload, and where (with PUT or POST).

TYPE: list[FilePickerUploadFile]

will_unmount #

will_unmount()