Question

When I tried to open a file in new window using the code below, it is downloading the document instead of opening in new window. When I open the downloaded document, it looks good.

But I want the document to be open in new window. Thanks for your help.

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();
    }
}
Était-ce utile?

La solution

Your content-disposition header is causing the browser to save the file instead of displaying it inline. You still need the content-type header, but try it after removing content-disposition.

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

If this header is used in a response with the application/octet- stream content-type, the implied suggestion is that the user agent should not display the response, but directly enter a `save response as...' dialog.

This has over time morphed into "the content should be saved directly if content-disposition is sent". Most browsers seem to behave this way, in my experience.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top