Skip to content

Uploader

Overview

Uploader is the equivalent of an <input type="file> HTML element except it uses a custom UI that better matches the look of Angular Material Components.

Examples

import base64

import mesop as me


@me.stateclass
class State:
  file: me.UploadedFile


@me.page(
  security_policy=me.SecurityPolicy(
    allowed_iframe_parents=["https://google.github.io"]
  ),
  path="/uploader",
)
def app():
  state = me.state(State)
  with me.box(style=me.Style(padding=me.Padding.all(15))):
    me.uploader(
      label="Upload Image",
      accepted_file_types=["image/jpeg", "image/png"],
      on_upload=handle_upload,
      type="flat",
      color="primary",
      style=me.Style(font_weight="bold"),
    )

    if state.file.size:
      with me.box(style=me.Style(margin=me.Margin.all(10))):
        me.text(f"File name: {state.file.name}")
        me.text(f"File size: {state.file.size}")
        me.text(f"File type: {state.file.mime_type}")

      with me.box(style=me.Style(margin=me.Margin.all(10))):
        me.image(src=_convert_contents_data_url(state.file))


def handle_upload(event: me.UploadEvent):
  state = me.state(State)
  state.file = event.file


def _convert_contents_data_url(file: me.UploadedFile) -> str:
  return (
    f"data:{file.mime_type};base64,{base64.b64encode(file.getvalue()).decode()}"
  )

API

uploader

This function creates an uploader.

PARAMETER DESCRIPTION
label

Upload button label.

TYPE: str

accepted_file_types

List of accepted file types. See the accept parameter.

TYPE: Sequence[str] | None DEFAULT: None

key

The component key.

TYPE: str | None DEFAULT: None

on_upload

File upload event handler.

TYPE: Callable[[UploadEvent], Any] | None DEFAULT: None

type

Type of button style to use

TYPE: Literal['raised', 'flat', 'stroked'] | None DEFAULT: None

color

Theme color palette of the button

TYPE: Literal['primary', 'accent', 'warn'] | None DEFAULT: None

disable_ripple

Whether the ripple effect is disabled or not.

TYPE: bool DEFAULT: False

disabled

Whether the button is disabled.

TYPE: bool DEFAULT: False

style

Style for the component.

TYPE: Style | None DEFAULT: None

UploadEvent dataclass

Bases: MesopEvent

Event for file uploads.

ATTRIBUTE DESCRIPTION
file

Uploaded file.

TYPE: UploadedFile

UploadedFile

Bases: BytesIO

Uploaded file contents and metadata.