upload.py 8.8 KB

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