ASP WebForms 文件下载仅在某些时候有效
ASP WebForms file download works only sometimes
我为订单开发了 add/remove/download 文件代码,效果很好。下载代码:
Response.Clear();
Response.ClearHeaders();
Response.ContentType = GetContentType(fileExtension);
Response.AppendHeader("Content-Disposition",
String.Format("attachment; filename=\"{0}\"", fileName));
Response.WriteFile(filePath);
Response.Flush();
Response.Close();
当代码在 DataList 的 OnItemCommand 方法中时一切正常。
protected void dlAttachemnts_OnItemCommand(object sender, DataListCommandEventArgs e)
{
if (e.CommandName == "btnDeleteAttachemnt")
{
...
}
if (e.CommandName == "btnDownloadAttachment")
{
// Download
}
}
但是当代码在其他页面的按钮中的Click方法时,下载不起作用。
protected void btnDownload_Click(object sender, EventArgs e)
{
// Download
}
我在 Global.asax.cs 中的 Application_Error() 中收到 HttpUnhandledException,消息为 "Server cannot set content type after HTTP headers have been sent"。
我仔细检查了 filePath、fileExtension 等,没问题。
我怀疑我同时发送了文件和页面,但我不熟悉 Web 表单,我不确定如何检查它和做什么(应用程序很旧,很大并且代码遗留).
感谢您的帮助! :)
我自己把按钮改成link
解决了
之前:
<asp:Button ID="btnDownload" runat="server" Text="Download" OnClick="btnDownload_Click" />
之后:
<a class="input-button-lookalike" href="/DownloadHandler.ashx?
fileName=myFile.txt" target='"_blank"'>Download</a>
我还添加了样式 input-button-lookalike 以便 link 与其他按钮一起看起来不错,并使用代码添加了处理程序 DownloadHandler.ashx:
public void ProcessRequest(HttpContext context)
{
var fileName = context.Request.QueryString["fileName"];
// Download as in question
}
我为订单开发了 add/remove/download 文件代码,效果很好。下载代码:
Response.Clear();
Response.ClearHeaders();
Response.ContentType = GetContentType(fileExtension);
Response.AppendHeader("Content-Disposition",
String.Format("attachment; filename=\"{0}\"", fileName));
Response.WriteFile(filePath);
Response.Flush();
Response.Close();
当代码在 DataList 的 OnItemCommand 方法中时一切正常。
protected void dlAttachemnts_OnItemCommand(object sender, DataListCommandEventArgs e)
{
if (e.CommandName == "btnDeleteAttachemnt")
{
...
}
if (e.CommandName == "btnDownloadAttachment")
{
// Download
}
}
但是当代码在其他页面的按钮中的Click方法时,下载不起作用。
protected void btnDownload_Click(object sender, EventArgs e)
{
// Download
}
我在 Global.asax.cs 中的 Application_Error() 中收到 HttpUnhandledException,消息为 "Server cannot set content type after HTTP headers have been sent"。
我仔细检查了 filePath、fileExtension 等,没问题。
我怀疑我同时发送了文件和页面,但我不熟悉 Web 表单,我不确定如何检查它和做什么(应用程序很旧,很大并且代码遗留).
感谢您的帮助! :)
我自己把按钮改成link
解决了之前:
<asp:Button ID="btnDownload" runat="server" Text="Download" OnClick="btnDownload_Click" />
之后:
<a class="input-button-lookalike" href="/DownloadHandler.ashx?
fileName=myFile.txt" target='"_blank"'>Download</a>
我还添加了样式 input-button-lookalike 以便 link 与其他按钮一起看起来不错,并使用代码添加了处理程序 DownloadHandler.ashx:
public void ProcessRequest(HttpContext context)
{
var fileName = context.Request.QueryString["fileName"];
// Download as in question
}