Skip to content

Commit 4231926

Browse files
committed
Making rx.download() more robust
1 parent 579e922 commit 4231926

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

reflex/.templates/web/utils/state.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,15 @@ export const applyEvent = async (event, socket, navigate, params) => {
269269
if (event.name == "_download") {
270270
const a = document.createElement("a");
271271
a.hidden = true;
272-
a.href = event.payload.url;
272+
if (event.payload.url.startsWith("DOWNLOAD_AS_BLOB:")) {
273+
const blob = new Blob(
274+
[event.payload.url.replace("DOWNLOAD_AS_BLOB:", "")],
275+
{ type: "application/octet-stream" },
276+
);
277+
a.href = URL.createObjectURL(blob);
278+
} else {
279+
a.href = event.payload.url;
280+
}
273281
// Special case when linking to uploaded files
274282
if (a.href.includes("getBackendURL(env.UPLOAD)")) {
275283
a.href = eval?.(

reflex/event.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1230,13 +1230,17 @@ def download(
12301230
url: str | Var | None = None,
12311231
filename: str | Var | None = None,
12321232
data: str | bytes | Var | None = None,
1233+
as_blob: bool | None = None,
1234+
mime_type: str | Var | None = None,
12331235
) -> EventSpec:
12341236
"""Download the file at a given path or with the specified data.
12351237
12361238
Args:
12371239
url: The URL to the file to download.
12381240
filename: The name that the file should be saved as after download.
12391241
data: The data to download.
1242+
as_blob: Downloads the provided `data` via JS `new Blob(...)`.
1243+
mime_type: Optional blob mime type when `as_blob` is set to True. Default is `application/octet-stream`.
12401244
12411245
Raises:
12421246
ValueError: If the URL provided is invalid, both URL and data are provided,
@@ -1258,13 +1262,20 @@ def download(
12581262

12591263
if filename is None:
12601264
filename = ""
1265+
if mime_type is None:
1266+
mime_type = "application/octet-stream"
12611267

12621268
if data is not None:
12631269
if url is not None:
12641270
msg = "Cannot provide both URL and data to download."
12651271
raise ValueError(msg)
12661272

1267-
if isinstance(data, str):
1273+
if as_blob:
1274+
url = f"DOWNLOAD_AS_BLOB:{data}"
1275+
if isinstance(data, Var):
1276+
url = f"DOWNLOAD_AS_BLOB:{data.to(str)}"
1277+
1278+
elif isinstance(data, str):
12681279
# Caller provided a plain text string to download.
12691280
url = "data:text/plain," + urllib.parse.quote(data)
12701281
elif isinstance(data, Var):
@@ -1293,6 +1304,7 @@ def download(
12931304
get_fn_signature(download),
12941305
url=url,
12951306
filename=filename,
1307+
mime_type=mime_type,
12961308
)
12971309

12981310

0 commit comments

Comments
 (0)