Przeglądaj źródła

file upload element

Falko Schindler 3 lat temu
rodzic
commit
502bab4b16
3 zmienionych plików z 37 dodań i 0 usunięć
  1. 5 0
      main.py
  2. 31 0
      nicegui/elements/upload.py
  3. 1 0
      nicegui/ui.py

+ 5 - 0
main.py

@@ -239,6 +239,11 @@ with example(ui.select):
         select = ui.select([1, 2, 3], value=1).props('inline')
         ui.select({1: 'One', 2: 'Two', 3: 'Three'}, value=1).props('inline').bind_value(select.value)
 
+with example(ui.upload):
+
+    ui.upload(on_upload=lambda files: content.set_text(files))
+    content = ui.label()
+
 with example(ui.plot):
     from matplotlib import pyplot as plt
     import numpy as np

+ 31 - 0
nicegui/elements/upload.py

@@ -0,0 +1,31 @@
+import justpy as jp
+from typing import Callable
+import base64
+from .element import Element
+from ..utils import handle_exceptions
+
+class Upload(Element):
+
+    def __init__(self,
+                 *,
+                 multiple: bool = False,
+                 on_upload: Callable = None,
+                 ):
+        """File Upload Element
+
+        :param multiple: allow uploading multiple files at once (default: False)
+        :param on_upload: callback to execute when a file is uploaded (list of bytearrays)
+        """
+        self.on_upload = handle_exceptions(on_upload)
+        view = jp.Form(enctype='multipart/form-data', classes='flex gap-4 items-center',
+                       submit=lambda s, m: self.submit(s, m))
+        jp.Input(type='file', multiple=multiple, a=view)
+        jp.QButton(type='submit', text='Upload', color='primary', a=view)
+
+        super().__init__(view)
+
+    def submit(self, _, msg):
+
+        for form_data in msg.form_data:
+            if form_data.type == 'file':
+                self.on_upload([base64.b64decode(f.file_content) for f in form_data.files])

+ 1 - 0
nicegui/ui.py

@@ -20,6 +20,7 @@ class Ui:
     from .elements.slider import Slider as slider
     from .elements.switch import Switch as switch
     from .elements.toggle import Toggle as toggle
+    from .elements.upload import Upload as upload
 
     from .elements.plot import Plot as plot
     from .elements.line_plot import LinePlot as line_plot