From d00907f9b3806cb2d94b6565527956475848a7a2 Mon Sep 17 00:00:00 2001 From: Sebastien Jourdain Date: Mon, 29 Aug 2022 15:47:02 -0600 Subject: [PATCH] feat(ClientFile): Add helper to handle multi-part upload file --- examples/00_howdoi/upload.py | 11 +++++--- trame/app/file_upload.py | 49 ++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 3 deletions(-) create mode 100644 trame/app/file_upload.py diff --git a/examples/00_howdoi/upload.py b/examples/00_howdoi/upload.py index ce5a2dee..ed1420b7 100644 --- a/examples/00_howdoi/upload.py +++ b/examples/00_howdoi/upload.py @@ -4,6 +4,7 @@ """ from trame.app import get_server +from trame.app.file_upload import ClientFile from trame.ui.vuetify import VAppLayout from trame.widgets import vuetify @@ -21,13 +22,17 @@ def file_uploaded(file_exchange, **kwargs): if file_exchange is None: return + file = ClientFile(file_exchange) file_name = file_exchange.get("name") file_size = file_exchange.get("size") file_time = file_exchange.get("lastModified") file_mime_type = file_exchange.get("type") - file_binary_content = file_exchange.get("content") - print(f"Got file {file_name} of size {file_size}") - print(file_binary_content) + file_binary_content = file_exchange.get( + "content" + ) # can be either list(bytes, ...), or bytes + print(file.info) + print(type(file.content)) # will always be bytes + # print(file_binary_content) if __name__ == "__main__": diff --git a/trame/app/file_upload.py b/trame/app/file_upload.py new file mode 100644 index 00000000..dc0be4a3 --- /dev/null +++ b/trame/app/file_upload.py @@ -0,0 +1,49 @@ +class ClientFile: + def __init__(self, file_state_variable=None): + self._name = None + self._size = None + self._time = None + self._mime_type = None + self._content = None + if file_state_variable is not None: + self._name = file_state_variable.get("name") + self._size = file_state_variable.get("size") + self._time = file_state_variable.get("lastModified") + self._mime_type = file_state_variable.get("type") + self._content = file_state_variable.get("content") + if isinstance(self._content, list): + self._content = b"".join(self._content) + + @property + def is_empty(self): + """Return true if the file is empty""" + return self._content is None + + @property + def name(self): + """File name""" + return self._name + + @property + def size(self): + """File size in Bytes""" + return self._size + + @property + def modified_time(self): + """Modified time""" + return self._time + + @property + def mime_type(self): + """Mime type of the file""" + return self._mime_type + + @property + def content(self): + """Bytes content of the file""" + return self._content + + @property + def info(self): + return f"File: {self.name} of size {self.size} and type {self.mime_type}"