Hi manishpand,
I have created sample code which fullfill requirement
HTML
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="File Name" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:LinkButton ID="lnkView" runat="server" Text="View" OnClick="View" CommandArgument='<%# Eval("Id") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
C#
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Id, Name FROM tblFiles";
cmd.Connection = con;
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
}
}
}
protected void View(object sender, EventArgs e)
{
string url = string.Format("Default.aspx?Id={0}", (sender as LinkButton).CommandArgument);
string script = "<script type='text/javascript'>window.open('" + url + "')</script>";
this.ClientScript.RegisterStartupScript(this.GetType(), "script", script);
}
Second Page:
HTML
<div>
<asp:Literal ID="ltEmbed" runat="server" />
</div>
C#
protected void Page_Load(object sender, EventArgs e)
{
string embed = "<object data=\"{0}{1}\" type=\"application/pdf\" width=\"500px\" height=\"300px\">";
embed += "If you are unable to view file, you can download from <a href = \"{0}{1}&download=1\">here</a>";
embed += " or download <a target = \"_blank\" href = \"http://get.adobe.com/reader/\">Adobe PDF Reader</a> to view the file.";
embed += "</object>";
ltEmbed.Text = string.Format(embed, ResolveUrl("~/FileCS.ashx?Id="), Request.QueryString["Id"]);
}
Add Handler
public void ProcessRequest(HttpContext context)
{
int id = int.Parse(context.Request.QueryString["Id"]);
byte[] bytes;
string fileName, contentType;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Name, Data, ContentType FROM tblFiles WHERE Id=@Id";
cmd.Parameters.AddWithValue("@Id", id);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["Data"];
contentType = sdr["ContentType"].ToString();
fileName = sdr["Name"].ToString();
}
con.Close();
}
}
context.Response.Buffer = true;
context.Response.Charset = "";
if (context.Request.QueryString["download"] == "1")
{
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
}
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.ContentType = "application/pdf";
context.Response.BinaryWrite(bytes);
context.Response.Flush();
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
I hope help you.