0

In my ASP.NET webforms I have this function to download file, which I get from Database. Please how to change it to display this file in new browser window? It's mostly pdf or image.

        protected void DownloadFile(object sender, EventArgs e)
    {
        string id = (sender as LinkButton).CommandArgument;
        byte[] bytes;
        string fileName;
        //string contentType;
        string constr = WebConfigurationManager.AppSettings["inputSqlCon"];
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = @"SELECT ATTACH_NAME, ATTACH
                FROM PA_REQ_NOTE_ATTACHMENTS 
                where ATTACH_ID = @Id";
                cmd.Parameters.AddWithValue("@Id", id);
                cmd.Connection = con;
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    sdr.Read();
                    bytes = (byte[])sdr["ATTACH"];
                    //contentType = sdr["ContentType"].ToString();
                    fileName = sdr["ATTACH_NAME"].ToString();
                }
                con.Close();
            }
        }
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        //Response.ContentType = contentType;
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
        Response.BinaryWrite(bytes);
        Response.Flush();
        Response.End();
    }
Pavel Matras
  • 329
  • 1
  • 5
  • 13
  • 1
    Does this answer your question? [How to use a Linkbutton to open into a new tab?](https://stackoverflow.com/questions/19573714/how-to-use-a-linkbutton-to-open-into-a-new-tab) – Pac0 May 25 '21 at 11:07
  • @Fildor it looks like asp.net webforms ;) – Cyril Iselin May 25 '21 at 11:09
  • @CyrilIselin Yep that would explain some things, haha. – Fildor May 25 '21 at 11:18
  • u should have a separate web form page for Previewing the file in the browser window (Preview.aspx). just pass the File Name or `ATTACH_ID` as a query string parameter. U can then just use window.open() on button click. Also u should have the `Content-Disposition` header as `inline` and not as `attachment` – Akshay G May 26 '21 at 11:09

0 Answers0