upload.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. """A file upload component."""
  2. from __future__ import annotations
  3. from typing import Dict, List, Optional
  4. from reflex.components.component import EVENT_ARG, Component
  5. from reflex.components.forms.input import Input
  6. from reflex.components.layout.box import Box
  7. from reflex.event import EventChain
  8. from reflex.vars import BaseVar, Var
  9. files_state = "const [files, setFiles] = useState([]);"
  10. upload_file = BaseVar(name="e => setFiles((files) => e)", type_=EventChain)
  11. # Use this var along with the Upload component to render the list of selected files.
  12. selected_files = BaseVar(name="files.map((f) => f.name)", type_=List[str])
  13. clear_selected_files = BaseVar(name="_e => setFiles((files) => [])", type_=EventChain)
  14. class Upload(Component):
  15. """A file upload component."""
  16. library = "react-dropzone"
  17. tag = "ReactDropzone"
  18. is_default = True
  19. # The list of accepted file types. This should be a dictionary of MIME types as keys and array of file formats as
  20. # values.
  21. # supported MIME types: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
  22. accept: Var[Optional[Dict[str, List]]]
  23. # Whether the dropzone is disabled.
  24. disabled: Var[bool]
  25. # The maximum number of files that can be uploaded.
  26. max_files: Var[int]
  27. # The maximum file size (bytes) that can be uploaded.
  28. max_size: Var[int]
  29. # The minimum file size (bytes) that can be uploaded.
  30. min_size: Var[int]
  31. # Whether to allow multiple files to be uploaded.
  32. multiple: Var[bool] = True # type: ignore
  33. # Whether to disable click to upload.
  34. no_click: Var[bool]
  35. # Whether to disable drag and drop.
  36. no_drag: Var[bool]
  37. # Whether to disable using the space/enter keys to upload.
  38. no_keyboard: Var[bool]
  39. @classmethod
  40. def create(cls, *children, **props) -> Component:
  41. """Create an upload component.
  42. Args:
  43. children: The children of the component.
  44. props: The properties of the component.
  45. Returns:
  46. The upload component.
  47. """
  48. # get only upload component props
  49. supported_props = cls.get_props()
  50. upload_props = {
  51. key: value for key, value in props.items() if key in supported_props
  52. }
  53. # The file input to use.
  54. upload = Input.create(type_="file")
  55. upload.special_props = {BaseVar(name="{...getInputProps()}", type_=None)}
  56. # The dropzone to use.
  57. zone = Box.create(
  58. upload,
  59. *children,
  60. **{k: v for k, v in props.items() if k not in supported_props},
  61. )
  62. zone.special_props = {BaseVar(name="{...getRootProps()}", type_=None)}
  63. # Create the component.
  64. return super().create(zone, on_drop=upload_file, **upload_props)
  65. def get_controlled_triggers(self) -> Dict[str, Var]:
  66. """Get the event triggers that pass the component's value to the handler.
  67. Returns:
  68. A dict mapping the event trigger to the var that is passed to the handler.
  69. """
  70. return {
  71. "on_drop": EVENT_ARG,
  72. }
  73. def _render(self):
  74. out = super()._render()
  75. out.args = ("getRootProps", "getInputProps")
  76. return out
  77. def _get_hooks(self) -> str | None:
  78. return (super()._get_hooks() or "") + files_state