upload.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import traceback
  2. import justpy as jp
  3. from typing import Awaitable, Callable, Optional, Union
  4. import base64
  5. from ..events import UploadEventArguments, handle_event
  6. from .element import Element
  7. class Upload(Element):
  8. def __init__(self,
  9. *,
  10. multiple: bool = False,
  11. on_upload: Optional[Union[Callable, Awaitable]] = None,
  12. ):
  13. """File Upload Element
  14. :param multiple: allow uploading multiple files at once (default: `False`)
  15. :param on_upload: callback to execute when a file is uploaded (list of bytearrays)
  16. """
  17. self.upload_handler = on_upload
  18. view = jp.Form(enctype='multipart/form-data', classes='flex gap-4 items-center',
  19. submit=lambda s, m: self.submit(s, m))
  20. jp.Input(type='file', multiple=multiple, a=view)
  21. jp.QButton(type='submit', text='Upload', color='primary', a=view)
  22. super().__init__(view)
  23. def submit(self, _, msg):
  24. try:
  25. for form_data in msg.form_data:
  26. if form_data.type == 'file':
  27. files = [base64.b64decode(f.file_content) for f in form_data.files]
  28. arguments = UploadEventArguments(sender=self, files=files)
  29. handle_event(self.upload_handler, arguments, update=self.parent_view)
  30. except Exception:
  31. traceback.print_exc()