简体   繁体   English

打开一个新的窗口 Codebehind ASP.net

[英]Opening a new Window Codebehind ASP.net

I have the following code:我有以下代码:

protected void Page_Load(object sender, EventArgs e)
{
        byte[] buffer = null;
        buffer = File.ReadAllBytes("C:\\myfile.pdf");
        HttpContext.Current.Response.ContentType = "application/pdf";
        HttpContext.Current.Response.OutputStream.Write(buffer, 0, buffer.Length);
        HttpContext.Current.Response.End();
}

I want to open a second window for the pfd file beside the current page, where the pageload comes from.我想在当前页面旁边为 pfd 文件打开第二个窗口,页面加载来自哪里。

There is no way to open a new window from a codebehind file.无法从代码隐藏文件打开新窗口。 The link to the page on which this Page_Load event is being fired must have the target="_blank" attribute to open it in a new window.指向触发此 Page_Load 事件的页面的链接必须具有target="_blank"属性才能在新窗口中打开它。 For example:例如:

<a href="DownloadPdf.aspx" target="_blank">Download PDF<a>

On a side note, if this is the only function of your ASPX file, you may want to consider using an HttpHandler instead.附带说明一下,如果这是您的 ASPX 文件的唯一功能,您可能需要考虑使用 HttpHandler 代替。

In order to do this you'll need to upload the PDF to a path in the application where it can be presented to the user, then register some javascript to open the PDF in a new window:为此,您需要将 PDF 上传到应用程序中可以呈现给用户的路径,然后注册一些 javascript 以在新窗口中打开 PDF:

protected void Page_Load(object sender, EventArgs e)
{
    byte[] buffer = null;
    buffer = File.ReadAllBytes("C:\\myfile.pdf");
    //save file to somewhere on server, for example in a folder called PDFs inside your application's root folder
    string newFilepath = Server.MapPath("~/PDFs/uploadedPDF.pdf");
    System.IO.FileStream savedPDF = File.Create(newFilepath);
    file.Write(buffer, 0, buffer.Length);
    file.Close();

    //register some javascript to open the new window
    Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenPDFScript", "window.open(\"/PDFs/uploadedPDF.pdf\");", true);
}

You can't do this from the response.你不能从响应中做到这一点。

If you have control of the hyperlink that leads to this page load, you can give it an attrbute target="_blank" , which will ask the browser to open that link in a new window.如果您可以控制导致此页面加载的超链接,您可以给它一个属性target="_blank" ,这将要求浏览器在新窗口中打开该链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM