add download event (#1797)
This commit is contained in:
parent
f2b0915aff
commit
b378827b83
@ -153,6 +153,15 @@ export const applyEvent = async (event, socket) => {
|
||||
navigator.clipboard.writeText(content);
|
||||
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") {
|
||||
alert(event.payload.message);
|
||||
|
@ -23,6 +23,7 @@ from .event import EventChain as EventChain
|
||||
from .event import FileUpload as upload_files
|
||||
from .event import clear_local_storage as clear_local_storage
|
||||
from .event import console_log as console_log
|
||||
from .event import download as download
|
||||
from .event import redirect as redirect
|
||||
from .event import remove_cookie as remove_cookie
|
||||
from .event import remove_local_storage as remove_local_storage
|
||||
|
@ -2,7 +2,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
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.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):
|
||||
"""Get the event from the given state.
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user