下载并重定向
本文关键字:重定向 下载 | 更新日期: 2023-09-27 18:30:18
我想下载一个.CSV 并将用户重定向到另一个页面。
这是我的代码
protected void btnExport_Click(object sender, EventArgs e)
{
string attachment = "attachment; filename=" + Request.QueryString["exportName"] + ".csv";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "application/ms-excel";
//CODE TO WRITE CSV
List<Company> companies = (List<Company>)Session["SelectedCompanies"];
foreach (Company company in companies)
{
HttpContext.Current.Response.Write(company.Name + ";");
HttpContext.Current.Response.Write(Environment.NewLine);
}
HttpContext.Current.Response.Redirect("otherpage.aspx", true);
}
但不幸的是,它只执行重定向,而不执行 ..CSV。
如果我用HttpContext.Current.Response.End();
替换HttpContext.Current.Response.Redirect("otherpage.aspx", true);
,那么它只下载.CSV 而不是重定向。
但我想两者兼而有之。
据
我所知,这两个操作无法在一个请求中完成,要么重定向用户,要么给文件。尝试通过两个动作来制作它。
在这种情况下,我所做的是:
-
隐藏 iframe
-
给这个Iframe我的下载网址(如download.ashx),同时改变我的页面内容。
在服务器上
public string DownloadViaIFrame(Page page, Download download)
{
string script = string.Format(
@"
var IsDownloaded=false;
domReady(function() {{
if (document.getElementById('DownloadIFrame')==undefined)
alert('DownloadIFrame not found');
else
{{
if (!IsDownloaded)
{{
{0};
IsDownloaded=true;
}}
}}
}});", GetJavasciptToDownloadViaIFrame(download));
ScriptManager.RegisterClientScriptBlock(page, typeof(Page), "download", script, true);
return script;
}
public string GetJavasciptToDownloadViaIFrame(Download download)
{
return string.Format("document.getElementById('DownloadIFrame').src='{0}'", GetDownloadLink(download));
}
这样,Iframe 就会命中服务器上的下载脚本,并返回客户端要下载的文件。客户同时看到其页面内容发生了变化,很高兴。
祝你好运
据
我所知,不可能同时执行这两个操作。尝试重定向到 otherPage.aspx,并在 otherPage 中注入一个 javascript 代码.aspx该代码在 onload 事件时连接到特定的"真实"下载页面