Upload
The Upload component can be used to upload files to the server.
You can pass components as children to customize its appearance. You can upload files by clicking on the component or by dragging and dropping files onto it.
Selecting a file will add it to the browser's file list, which can be rendered
on the frontend using the rx.selected_files(id)
special Var. To clear the
selected files, you can use another special Var rx.clear_selected_files(id)
as
an event handler.
To upload the file(s), you need to bind an event handler and pass the special
rx.upload_files(upload_id=id)
event arg to it.
A full example is shown below.
In the example below, the upload component accepts a maximum number of 5 files of specific types. It also disables the use of the space or enter key in uploading files.
To use a one-step upload, bind the event handler to the rx.upload
component's
on_drop
trigger.
Handling the Upload
Your event handler should be an async function that accepts a single argument,
files: list[UploadFile]
, which will contain FastAPI UploadFile instances.
You can read the files and save them anywhere as shown in the example.
In your UI, you can bind the event handler to a trigger, such as a button
on_click
event or upload on_drop
event, and pass in the files using
rx.upload_files()
.
Saving the File
By convention, Reflex provides the function rx.get_upload_dir()
to get the directory where uploaded files may be saved. The upload dir comes from the environment variable REFLEX_UPLOADED_FILES_DIR
, or ./uploaded_files
if not specified.
The backend of your app will mount this uploaded files directory on /_upload
without restriction. Any files uploaded via this mechanism will automatically be publicly accessible. To get the URL for a file inside the upload dir, use the rx.get_upload_url(filename)
function in a frontend component.
When using the Reflex hosting service, the uploaded files directory is not persistent and will be cleared on every deployment. For persistent storage of uploaded files, it is recommended to use an external service, such as S3.
Cancellation
The id
provided to the rx.upload
component can be passed to the special event handler rx.cancel_upload(id)
to stop uploading on demand. Cancellation can be triggered directly by a frontend event trigger, or it can be returned from a backend event handler.
Progress
The rx.upload_files
special event arg also accepts an on_upload_progress
event trigger which will be fired about every second during the upload operation to report the progress of the upload. This can be used to update a progress bar or other UI elements to show the user the progress of the upload.
The progress
dictionary contains the following keys: