44import inspect
55import sys
66import types
7- import urllib .parse
87from base64 import b64encode
98from collections .abc import Callable , Mapping , Sequence
109from functools import lru_cache , partial
@@ -1230,13 +1229,15 @@ def download(
12301229 url : str | Var | None = None ,
12311230 filename : str | Var | None = None ,
12321231 data : str | bytes | Var | None = None ,
1232+ mime_type : str | Var | None = None ,
12331233) -> EventSpec :
12341234 """Download the file at a given path or with the specified data.
12351235
12361236 Args:
12371237 url: The URL to the file to download.
12381238 filename: The name that the file should be saved as after download.
12391239 data: The data to download.
1240+ mime_type: The mime type of the data to download.
12401241
12411242 Raises:
12421243 ValueError: If the URL provided is invalid, both URL and data are provided,
@@ -1265,9 +1266,15 @@ def download(
12651266 raise ValueError (msg )
12661267
12671268 if isinstance (data , str ):
1269+ if mime_type is None :
1270+ mime_type = "text/plain"
12681271 # Caller provided a plain text string to download.
1269- url = "data:text/plain," + urllib .parse .quote (data )
1272+ url = f"data:{ mime_type } ;base64," + b64encode (data .encode ("utf-8" )).decode (
1273+ "utf-8"
1274+ )
12701275 elif isinstance (data , Var ):
1276+ if mime_type is None :
1277+ mime_type = "text/plain"
12711278 # Need to check on the frontend if the Var already looks like a data: URI.
12721279
12731280 is_data_url = (data .js_type () == "string" ) & (
@@ -1278,12 +1285,14 @@ def download(
12781285 url = cond (
12791286 is_data_url ,
12801287 data .to (str ),
1281- "data:text/plain ," + data .to_string (),
1288+ f "data:{ mime_type } ," + data .to_string (),
12821289 )
12831290 elif isinstance (data , bytes ):
1291+ if mime_type is None :
1292+ mime_type = "application/octet-stream"
12841293 # Caller provided bytes, so base64 encode it as a data: URI.
12851294 b64_data = b64encode (data ).decode ("utf-8" )
1286- url = "data:application/octet-stream ;base64," + b64_data
1295+ url = f "data:{ mime_type } ;base64," + b64_data
12871296 else :
12881297 msg = f"Invalid data type { type (data )} for download. Use `str` or `bytes`."
12891298 raise ValueError (msg )
0 commit comments