使用C#与ASP.NET下载PDF文件失败问题求助
问题排查与修复方案
你的代码核心问题出在Content-Disposition响应头的filename参数,同时存在冗余设置,以下是具体修复步骤:
1. 修正文件名参数
你当前给filename传了服务器相对路径~/Template/Self_Declaration.pdf,客户端浏览器无法识别这个路径,必须直接用纯文件名:
// 用变量fileName更易维护 Response.AddHeader("content-disposition", $"attachment; filename={fileName}");
2. 移除重复的Content-Type设置
代码里重复设置了两次Content-Type,保留其中一个即可,推荐直接用Response.ContentType:
// 删除这一行:Response.AddHeader("Content-Type", "application/pdf"); Response.ContentType = "application/pdf";
3. 优化文件传输方式(可选但推荐)
用Response.TransmitFile替代Response.WriteFile,它不需要把整个文件加载到内存,性能更优:
Response.TransmitFile(file.FullName);
4. 添加文件大小头(可选)
补充Content-Length头,让浏览器能准确识别文件大小,避免下载异常:
Response.AddHeader("Content-Length", file.Length.ToString());
完整修复后的代码
protected void btn_Download_Template_Click(object sender, EventArgs e) { string fileName = "Self_Declaration.pdf"; string mainPath = Server.MapPath("~/Template/Self_Declaration.pdf"); FileInfo file = new FileInfo(mainPath); if (file.Exists) { Response.Clear(); Response.ClearHeaders(); Response.ClearContent(); Response.AddHeader("content-disposition", $"attachment; filename={fileName}"); Response.ContentType = "application/pdf"; Response.AddHeader("Content-Length", file.Length.ToString()); Response.TransmitFile(file.FullName); Response.Flush(); Response.End(); } else { Response.Write("文件不存在。"); } }
额外排查点
- 如果按钮在
UpdatePanel内,必须将按钮设置为PostBackTrigger,异步回发无法触发文件下载 - 确认服务器上
~/Template/Self_Declaration.pdf路径确实存在文件,且应用程序池账号有该文件的读取权限
内容的提问来源于stack exchange,提问作者johnjs
相关产品推荐
相关产品推荐

