upload.py 7.0 KB

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