upload.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. """A file upload component."""
  2. from __future__ import annotations
  3. import os
  4. from pathlib import Path
  5. from typing import Callable, ClassVar, Dict, List, Optional
  6. from reflex.components.component import Component, ComponentNamespace, MemoizationLeaf
  7. from reflex.components.el.elements.forms import Input
  8. from reflex.components.radix.themes.layout.box import Box
  9. from reflex.constants import Dirs
  10. from reflex.event import (
  11. CallableEventSpec,
  12. EventChain,
  13. EventHandler,
  14. EventSpec,
  15. call_event_fn,
  16. call_script,
  17. parse_args_spec,
  18. )
  19. from reflex.utils.imports import ImportVar
  20. from reflex.vars import VarData
  21. from reflex.vars.base import CallableVar, LiteralVar, Var
  22. from reflex.vars.sequence import LiteralStringVar
  23. from reflex.components.radix.themes.components.button import button
  24. from reflex.components.lucide import icon
  25. DEFAULT_UPLOAD_ID: str = "default"
  26. upload_files_context_var_data: VarData = VarData(
  27. imports={
  28. "react": "useContext",
  29. f"/{Dirs.CONTEXTS_PATH}": "UploadFilesContext",
  30. },
  31. hooks={
  32. "const [filesById, setFilesById] = useContext(UploadFilesContext);": None,
  33. },
  34. )
  35. @CallableVar
  36. def upload_file(id_: str = DEFAULT_UPLOAD_ID) -> Var:
  37. """Get the file upload drop trigger.
  38. This var is passed to the dropzone component to update the file list when a
  39. drop occurs.
  40. Args:
  41. id_: The id of the upload to get the drop trigger for.
  42. Returns:
  43. A var referencing the file upload drop trigger.
  44. """
  45. id_var = LiteralStringVar.create(id_)
  46. var_name = f"""e => setFilesById(filesById => {{
  47. const updatedFilesById = Object.assign({{}}, filesById);
  48. updatedFilesById[{str(id_var)}] = e;
  49. return updatedFilesById;
  50. }})
  51. """
  52. return Var(
  53. _js_expr=var_name,
  54. _var_type=EventChain,
  55. _var_data=VarData.merge(
  56. upload_files_context_var_data, id_var._get_all_var_data()
  57. ),
  58. )
  59. @CallableVar
  60. def selected_files(id_: str = DEFAULT_UPLOAD_ID) -> Var:
  61. """Get the list of selected files.
  62. Args:
  63. id_: The id of the upload to get the selected files for.
  64. Returns:
  65. A var referencing the list of selected file paths.
  66. """
  67. id_var = LiteralStringVar.create(id_)
  68. return Var(
  69. _js_expr=f"(filesById[{str(id_var)}] ? filesById[{str(id_var)}].map((f) => (f.path || f.name)) : [])",
  70. _var_type=List[str],
  71. _var_data=VarData.merge(
  72. upload_files_context_var_data, id_var._get_all_var_data()
  73. ),
  74. ).guess_type()
  75. @CallableEventSpec
  76. def clear_selected_files(id_: str = DEFAULT_UPLOAD_ID) -> EventSpec:
  77. """Clear the list of selected files.
  78. Args:
  79. id_: The id of the upload to clear.
  80. Returns:
  81. An event spec that clears the list of selected files when triggered.
  82. """
  83. # UploadFilesProvider assigns a special function to clear selected files
  84. # into the shared global refs object to make it accessible outside a React
  85. # component via `call_script` (otherwise backend could never clear files).
  86. return call_script(f"refs['__clear_selected_files']({id_!r})")
  87. def cancel_upload(upload_id: str) -> EventSpec:
  88. """Cancel an upload.
  89. Args:
  90. upload_id: The id of the upload to cancel.
  91. Returns:
  92. An event spec that cancels the upload when triggered.
  93. """
  94. return call_script(
  95. f"upload_controllers[{str(LiteralVar.create(upload_id))}]?.abort()"
  96. )
  97. def get_upload_dir() -> Path:
  98. """Get the directory where uploaded files are stored.
  99. Returns:
  100. The directory where uploaded files are stored.
  101. """
  102. Upload.is_used = True
  103. uploaded_files_dir = Path(
  104. os.environ.get("REFLEX_UPLOADED_FILES_DIR", "./uploaded_files")
  105. )
  106. uploaded_files_dir.mkdir(parents=True, exist_ok=True)
  107. return uploaded_files_dir
  108. uploaded_files_url_prefix = Var(
  109. _js_expr="getBackendURL(env.UPLOAD)",
  110. _var_data=VarData(
  111. imports={
  112. f"/{Dirs.STATE_PATH}": "getBackendURL",
  113. "/env.json": ImportVar(tag="env", is_default=True),
  114. }
  115. ),
  116. ).to(str)
  117. def get_upload_url(file_path: str) -> Var[str]:
  118. """Get the URL of an uploaded file.
  119. Args:
  120. file_path: The path of the uploaded file.
  121. Returns:
  122. The URL of the uploaded file to be rendered from the frontend (as a str-encoded Var).
  123. """
  124. Upload.is_used = True
  125. return uploaded_files_url_prefix + "/" + file_path
  126. def _on_drop_spec(files: Var):
  127. """Args spec for the on_drop event trigger.
  128. Args:
  129. files: The files to upload.
  130. Returns:
  131. Signature for on_drop handler including the files to upload.
  132. """
  133. return [files]
  134. class UploadFilesProvider(Component):
  135. """AppWrap component that provides a dict of selected files by ID via useContext."""
  136. library = f"/{Dirs.CONTEXTS_PATH}"
  137. tag = "UploadFilesProvider"
  138. class Upload(MemoizationLeaf):
  139. """A file upload component."""
  140. library = "react-dropzone@14.2.9"
  141. tag = "ReactDropzone"
  142. is_default = True
  143. # The list of accepted file types. This should be a dictionary of MIME types as keys and array of file formats as
  144. # values.
  145. # supported MIME types: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
  146. accept: Var[Optional[Dict[str, List]]]
  147. # Whether the dropzone is disabled.
  148. disabled: Var[bool]
  149. # The maximum number of files that can be uploaded.
  150. max_files: Var[int]
  151. # The maximum file size (bytes) that can be uploaded.
  152. max_size: Var[int]
  153. # The minimum file size (bytes) that can be uploaded.
  154. min_size: Var[int]
  155. # Whether to allow multiple files to be uploaded.
  156. multiple: Var[bool] = True # type: ignore
  157. # Whether to disable click to upload.
  158. no_click: Var[bool]
  159. # Whether to disable drag and drop.
  160. no_drag: Var[bool]
  161. # Whether to disable using the space/enter keys to upload.
  162. no_keyboard: Var[bool]
  163. # Marked True when any Upload component is created.
  164. is_used: ClassVar[bool] = False
  165. # Fired when files are dropped.
  166. on_drop: EventHandler[_on_drop_spec]
  167. @classmethod
  168. def create(cls, *children, **props) -> Component:
  169. """Create an upload component.
  170. Args:
  171. *children: The children of the component.
  172. **props: The properties of the component.
  173. Returns:
  174. The upload component.
  175. """
  176. # Mark the Upload component as used in the app.
  177. cls.is_used = True
  178. # Apply the default classname
  179. given_class_name = props.pop("class_name", [])
  180. if isinstance(given_class_name, str):
  181. given_class_name = [given_class_name]
  182. props["class_name"] = ["rx-Upload", *given_class_name]
  183. # get only upload component props
  184. supported_props = cls.get_props().union({"on_drop"})
  185. upload_props = {
  186. key: value for key, value in props.items() if key in supported_props
  187. }
  188. # The file input to use.
  189. upload = Input.create(type="file")
  190. upload.special_props = [Var(_js_expr="{...getInputProps()}", _var_type=None)]
  191. # The dropzone to use.
  192. zone = Box.create(
  193. upload,
  194. *children,
  195. **{k: v for k, v in props.items() if k not in supported_props},
  196. )
  197. zone.special_props = [Var(_js_expr="{...getRootProps()}", _var_type=None)]
  198. # Create the component.
  199. upload_props["id"] = props.get("id", DEFAULT_UPLOAD_ID)
  200. if upload_props.get("on_drop") is None:
  201. # If on_drop is not provided, save files to be uploaded later.
  202. upload_props["on_drop"] = upload_file(upload_props["id"])
  203. else:
  204. on_drop = upload_props["on_drop"]
  205. if isinstance(on_drop, Callable):
  206. # Call the lambda to get the event chain.
  207. on_drop = call_event_fn(on_drop, _on_drop_spec) # type: ignore
  208. if isinstance(on_drop, EventSpec):
  209. # Update the provided args for direct use with on_drop.
  210. on_drop = on_drop.with_args(
  211. args=tuple(
  212. cls._update_arg_tuple_for_on_drop(arg_value)
  213. for arg_value in on_drop.args
  214. ),
  215. )
  216. upload_props["on_drop"] = on_drop
  217. return super().create(
  218. zone,
  219. **upload_props,
  220. )
  221. @classmethod
  222. def _update_arg_tuple_for_on_drop(cls, arg_value: tuple[Var, Var]):
  223. """Helper to update caller-provided EventSpec args for direct use with on_drop.
  224. Args:
  225. arg_value: The arg tuple to update (if necessary).
  226. Returns:
  227. The updated arg_value tuple when arg is "files", otherwise the original arg_value.
  228. """
  229. if arg_value[0]._js_expr == "files":
  230. placeholder = parse_args_spec(_on_drop_spec)[0]
  231. return (arg_value[0], placeholder)
  232. return arg_value
  233. def _render(self):
  234. out = super()._render()
  235. out.args = ("getRootProps", "getInputProps")
  236. return out
  237. @staticmethod
  238. def _get_app_wrap_components() -> dict[tuple[int, str], Component]:
  239. return {
  240. (5, "UploadFilesProvider"): UploadFilesProvider.create(),
  241. }
  242. class StyledUpload(Upload):
  243. """The styled Upload Component."""
  244. @classmethod
  245. def create(cls, *children, **props) -> Component:
  246. """Create the styled upload component.
  247. Args:
  248. *children: The children of the component.
  249. **props: The properties of the component.
  250. Returns:
  251. The styled upload component.
  252. """
  253. # Set default props.
  254. if not children:
  255. children = [button("Upload Files", icon("upload", size=12), align_items="center")]
  256. # Mark the Upload component as used in the app.
  257. Upload.is_used = True
  258. return super().create(
  259. *children,
  260. **props,
  261. )
  262. class UploadNamespace(ComponentNamespace):
  263. """Upload component namespace."""
  264. root = Upload.create
  265. __call__ = StyledUpload.create
  266. upload = UploadNamespace()