在新窗口中打开jpg / pdf

时间:2014-04-28 18:48:51

标签: c# asp.net response.transmitfile

当我尝试使用下面的代码在新窗口中打开文件时,它正在下载文档而不是在新窗口中打开。当我打开下载的文档时,它看起来不错。

But I want the document to be open in new window。谢谢你的帮助。

WebForm2Test.aspx

<a href="WebForm1Test.aspx" onclick="window.open('WebForm1Test.aspx','_blank')">WebForm1Test.aspx  </a>

WebForm1Test.aspx.cs

public partial class WebForm1Test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Writes Document
        System.IO.MemoryStream outStream = new System.IO.MemoryStream(Some_Base64_String);
        HttpContext.Current.Response.Expires = 0;
        HttpContext.Current.Response.Buffer = true;
        HttpContext.Current.Response.ClearContent();
        string STR_File_Name = "test"
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + test);

        //Known Content Types            
        if (OBJ_Document.CH_Document_Extension.ToUpper() == "JPG")
        {
            HttpContext.Current.Response.AppendHeader("Content-Type", "image/jpeg");
        }
        if (OBJ_Document.CH_Document_Extension.ToUpper() == "JPEG")
        {
            HttpContext.Current.Response.AppendHeader("Content-Type", "image/jpeg");
        }

        if (OBJ_Document.CH_Document_Extension.ToUpper() == "PDF")
        {
               HttpContext.Current.Response.AppendHeader("Content-Type", "application/pdf");
        }            

        using (FileStream file = new FileStream("c:\\file.bin", FileMode.Create, System.IO.FileAccess.Write))
        {
            byte[] bytes = new byte[outStream.Length];
            outStream.Read(bytes, 0, (int)outStream.Length);
            file.Write(bytes, 0, bytes.Length);
            outStream.Close();
        }

        HttpContext.Current.Response.TransmitFile("c:\\file.bin");
        outStream.Close();
        HttpContext.Current.Response.End();
    }
}

1 个答案:

答案 0 :(得分:0)

您的内容处置标头导致浏览器保存文件而不是内联显示。您仍然需要内容类型标题,但在删除内容处置后尝试使用它。

http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.5.1

  

如果在带有application / octet-stream内容类型的响应中使用此标头,则隐含的建议是用户代理不应显示响应,而是直接输入“保存响应为...&#39 ;对话框。

随着时间的推移,这已经变成了#34;如果内容处置被发送,则应该直接保存内容&#34;。根据我的经验,大多数浏览器似乎都是这样做的。