Plotly-Dash dbc.Button在Linux环境下无法正常下载文件问题
问题原因
直接通过href指向静态Excel文件的方式,在Linux环境下可能因为Web服务器默认以文本模式传输二进制文件,导致文件内容被错误编码,最终下载的文件损坏、体积变小。Windows系统下的服务器配置通常默认处理二进制文件的方式更宽松,所以没有触发这个问题。
修复方案
改用Dash的dcc.Download组件配合回调函数来处理文件下载,确保文件以二进制流的形式正确传输:
更新布局代码:
添加dcc.Download组件,并修改dbc.Button去掉href、external_link参数,改为触发回调的按钮:from dash import dcc # 布局中添加按钮和下载组件 dbc.Button( children=["Download Template"], id="download-template-btn", style={ "background-color": "#4CAF50", "border": "none", "fontWeight": "bold", "width":"200px", "marginBottom":"20px" } ), dcc.Download(id="download-template")添加回调函数:
编写回调读取Excel文件的二进制内容,并返回给下载组件:from dash import callback, Output, Input import os @callback( Output("download-template", "data"), Input("download-template-btn", "n_clicks"), prevent_initial_call=True ) def download_template(n_clicks): # 拼接文件路径,确保指向正确的静态文件位置 file_path = os.path.join("static", "Template.xlsx") # 以二进制模式读取文件,避免编码转换损坏内容 with open(file_path, "rb") as f: file_content = f.read() # 返回下载数据,明确指定文件类型为Excel格式 return dict( content=file_content, filename="Template.xlsx", type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" )
额外注意事项
- 可以通过
print(os.path.abspath(file_path))验证文件路径在Linux环境下是否正确,确保文件存在。 - 检查Linux服务器的文件权限,确保Dash运行进程有权限读取该Excel文件。
内容的提问来源于stack exchange,提问作者Jatin Munjal
相关产品推荐
相关产品推荐

