
本文详解如何在 dash 应用中,通过回调函数将动态生成的 plotly 图形实时导出为本地 html 文件,解决常见“下载空白页”问题,关键在于使用 `dcc.download` 组件与 `dcc.send_file()` 配合服务端临时文件写入。
在 Dash 中直接通过 href="data:text/html;base64,..." 方式预生成 HTML 下载链接是行不通的——因为该链接在应用初始化时就已固化,而图形(figure)是在用户交互后由回调动态生成的,初始时 buffer 为空,且无法在客户端实时更新 href 属性。正确做法是:将 HTML 文件写入服务端临时路径,并在用户点击下载按钮时,由回调触发 dcc.send_file() 发送该文件。
以下是推荐的完整实现方案:
✅ 正确步骤概览
- 移除硬编码的 href,改用 html.Button + dcc.Download 组合;
- 在图形更新回调中(如 update_line_chart),调用 fig.write_html("output.html") 将当前图形保存为 HTML 文件;
- 新增独立下载回调,监听按钮点击(n_clicks),返回 dcc.send_file("output.html");
- 确保 dcc.Download 组件在布局中声明,并通过 id 与回调关联。
✅ 完整可运行代码示例
from dash import Dash, dcc, html, Input, Output, callback
import plotly.express as px
app = Dash(__name__)
# 使用内置示例数据(请替换为你自己的 df)
df = px.data.gapminder().query("year == 2007")
app.layout = html.Div([
html.H4('交互式散点图'),
dcc.Graph(id="graph"),
dcc.Checklist(
id="checklist",
options=["Asia", "Europe", "Americas", "Oceania", "Africa"],
value=["Asia", "Europe"],
inline=True
),
html.Button("下载为 HTML", id="download-btn"),
dcc.Download(id="download-component") # 必须声明此组件
])
# 更新图形并同步保存 HTML 文件
@app.callback(
Output("graph", "figure"),
Input("checklist", "value")
)
def update_graph(continents):
dff = df[df["continent"].isin(continents)]
fig = px.scatter(
dff, x="gdpPercap", y="lifeExp",
size="pop", color="continent",
hover_name="country", log_x=True, size_max=60
)
# ✅ 关键:每次更新图形后立即写入 HTML 文件
fig.write_html("plotly_export.html")
return fig
# 响应下载按钮点击,发送 HTML 文件
@app.callback(
Output("download-component", "data"),
Input("download-btn", "n_clicks"),
prevent_initial_call=True
)
def trigger_download(n_clicks):
# ✅ 关键:返回 dcc.send_file(),Dash 自动处理文件流与响应头
return dcc.send_file("plotly_export.html")⚠️ 注意事项
- 文件路径安全:生产环境请使用 tempfile.mktemp() 或 os.path.join(tempfile.gettempdir(), ...) 生成唯一临时路径,避免多用户并发覆盖;
- 跨平台兼容性:fig.write_html() 生成的 HTML 是自包含的(含内联 JS/CSS),无需网络依赖,双击即可离线查看;
- 不要混用 b64encode + href:该方式仅适用于静态、初始化即确定的内容;动态图形必须走服务端文件流;
- prevent_initial_call=True 必须添加:防止应用启动时自动触发下载(n_clicks 初始为 None);
- 若需支持多次下载不同图形,建议为每次生成带时间戳的文件名(如 f"plot_{int(time.time())}.html")。
通过以上结构,你就能稳定、可靠地实现 Dash 中 Plotly 图形的 HTML 导出功能——图形随筛选实时更新,HTML 文件随点击即时生成并下载。











