[英]How to close the window after response?
我正在使用ASP.NET和C#。 我正在生成pdf並將其發送到使用
response.TransmitFile(file);
因此,在此之后,我需要關閉此窗口。我嘗試編寫用於關閉的動態腳本,但這沒有用。
在按鈕上單擊,我正在使用此代碼打開窗口。
window.open("Export.aspx?JobNumbers=" + jobnums,'',"resizable=0,scrollbars=0,status=0,height=200,width=500");
在export.cs的頁面加載中,我正在使用itextsharp創建pdf。然后使用它進行搜索。在按鈕的buttonclick上調用它,該按鈕使用
string script = "var btn = document.getElementById('" + Button1.ClientID + "');";
script += "btn.click();";
Page.ClientScript.RegisterStartupScript(this.GetType(), "Eport", script, true);
這是按鈕的onclick事件。
protected void StartExport(object sender, EventArgs e)
{
response.Clear();
response.ContentType = "application/pdf";
response.AddHeader("content-disposition", "attachment;filename=" + Path.GetFileName(strFilePath));
response.TransmitFile(strFilePath);
response.Flush();
}
在此之后,我需要關閉此export.aspx窗口,以供使用。
Page.ClientScript.RegisterStartupScript(this.GetType(), "Export", "window.onfocus=function(){window.close();}", true);
和
HttpContext.Current.Response.Write("<script>window.onfocus=function(){window.close();}</script>");
但是沒有用。
可能嗎?
您應該嘗試這樣的事情:
<script>
$.get('/call/the/page.aspx'); // Send a request to the page from which you Transmit the file
window.setTimeOut(function() { window.close(); }, 5000);
</script>
這將嘗試在5秒鍾后關閉窗口,留出足夠的時間開始下載。
您必須將其放置在頁面中,然后在彈出窗口中打開該頁面,以便該腳本執行,請求文件並自行關閉。
在body標簽html上,您必須設置事件unload =“ window.close()”。 這對我有用
我建議寫一個HttpHandler:
/// <summary>
/// here is your server-side file generator
/// </summary>
public class export : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
// get some id from query string
string someid = context.Request.QueryString["id"];
try
{
...
context.Response.ContentType = "application/pdf";
context.Response.HeaderEncoding = System.Text.Encoding.UTF8;
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
context.Response.AppendHeader("Content-Disposition", "attachment; filename=filename.pdf");
context.Response.Write(yourPDF);
/* or context.Response.WriteFile(...); */
}
catch (Exception ex)
{
/* exception handling */
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
不要忘記在Web.config中注冊它:
<system.webServer>
<handlers>
<add name="/export_GET" path="/export" verb="GET" type="YourNamespace.export" preCondition="integratedMode,runtimeVersionv4.0" resourceType="Unspecified" />
</handlers>
</system.webServer>
之后,您只需要像下面這樣從javascript調用此處理程序:
ExportFile: function () {
...
var url = "http://" + window.location.hostname + ":4433/export?cid=" + id;
window.open(url);
}
它會顯示保存對話框,而無需手動關閉新窗口(它將自動關閉)。
由於很明顯您無法關閉瀏覽器由於下載文件而創建的窗口(例如,已下載文件列表/您想打開提示),因此我認為問題是“如何關閉初始化的托管頁面”獲取PDF”操作。
由於無法讓頁面知道文件下載的完成情況,因此您可能需要詢問服務器(即AJAX erquest)下載是否完成-這將需要一些服務器端代碼來跟蹤下載(並且您可能無法使用會話狀態存儲下載狀態,因為它將被其他請求鎖定)。 確認下載完成后,您可以關閉窗口。 請注意,由用戶打開的關閉窗口將失敗,或者至少顯示“您是否真的要關閉”的確認...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.