add download event (#1797)

This commit is contained in:
Thomas Brandého 2023-09-13 18:56:00 +02:00 committed by GitHub
parent f2b0915aff
commit b378827b83
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 45 additions and 7 deletions

View File

@ -153,6 +153,15 @@ export const applyEvent = async (event, socket) => {
navigator.clipboard.writeText(content); navigator.clipboard.writeText(content);
return false; return false;
} }
if (event.name == "_download") {
const a = document.createElement('a');
a.hidden = true;
a.href = event.payload.url;
a.download = event.payload.filename;
a.click();
a.remove();
return false;
}
if (event.name == "_alert") { if (event.name == "_alert") {
alert(event.payload.message); alert(event.payload.message);

View File

@ -23,6 +23,7 @@ from .event import EventChain as EventChain
from .event import FileUpload as upload_files from .event import FileUpload as upload_files
from .event import clear_local_storage as clear_local_storage from .event import clear_local_storage as clear_local_storage
from .event import console_log as console_log from .event import console_log as console_log
from .event import download as download
from .event import redirect as redirect from .event import redirect as redirect
from .event import remove_cookie as remove_cookie from .event import remove_cookie as remove_cookie
from .event import remove_local_storage as remove_local_storage from .event import remove_local_storage as remove_local_storage

View File

@ -2,7 +2,7 @@
from __future__ import annotations from __future__ import annotations
import inspect import inspect
from typing import Any, Callable, Dict, List, Tuple from typing import Any, Callable, Dict, List, Optional, Tuple
from reflex import constants from reflex import constants
from reflex.base import Base from reflex.base import Base
@ -330,6 +330,34 @@ def set_clipboard(content: str) -> EventSpec:
) )
def download(url: str, filename: Optional[str] = None) -> EventSpec:
"""Download the file at a given path.
Args:
url : The URL to the file to download.
filename : The name that the file should be saved as after download.
Raises:
ValueError: If the URL provided is invalid.
Returns:
EventSpec: An event to download the associated file.
"""
if not url.startswith("/"):
raise ValueError("The URL argument should start with a /")
# if filename is not provided, infer it from url
if filename is None:
filename = url.rpartition("/")[-1]
return server_side(
"_download",
get_fn_signature(download),
url=url,
filename=filename,
)
def get_event(state, event): def get_event(state, event):
"""Get the event from the given state. """Get the event from the given state.