Following code helps to Retrieve the file from the sql table
The following code sample shows how to retrieve the file from the sql table as a download link.
once you get the fileid from database assign the text to hyperlink which shown below, once click that link it shows option to download or open the file with use of handler class.
<asp:HyperLink ID="view1" Text="View or Download" runat="Server" NavigateUrl='<%# Eval("Fileid", "Handler.ashx?Fileid={0}") %>' Target="_blank"> </asp:HyperLink>
handler file:
<%@ WebHandler Language="C#" Class="Handler" %>
using System; using System.Web; using System.Data; using System.Data.SqlClient;
public class Handler : IHttpHandler { string constr = "Data Source=DemoServer;Initial Catalog=HRM;User ID=sa;Password=sa123456"; //DataSet ds=new DataSet(); SqlCommand cmd = new SqlCommand(); public void ProcessRequest(HttpContext context) { // get the file id Guid Fileid = new Guid(context.Request.QueryString["Fileid"]);
cmd.Connection = new SqlConnection(constr); cmd.CommandText = "select * from [Filestbl] where Fileid = @Fileid"; cmd.Parameters.Add("@Fileid", SqlDbType.UniqueIdentifier).Value = Fileid; cmd.Connection.Open(); SqlDataReader reader = cmd.ExecuteReader(); if (reader.Read()) { // flush out the binary data to the user context.Response.Clear(); context.Response.ContentType = (string)reader["filetype"]; context.Response.AddHeader("Content-Disposition", String.Format("inline;filename={0};", reader["filename"].ToString())); context.Response.AddHeader("Content-Length", reader["filesize"].ToString()); context.Response.BinaryWrite((byte[])reader["filecontent"]); context.Response.End(); }
} public bool IsReusable { get { return false; } } }
|
| Author: Kapil Dhawan 18 Jun 2008 | Member Level: Gold Points : 2 |
Hello Nice piece of code Thanks for sharing your knowledge with us. I hope to see more good code from your side This code will help lots of guys Thanks to you Regards, Kapil
|