Search code examples
c#asp.netsql-server-2008bytevarbinarymax

How can I make a download link which downloads data directly from a DB in ASP.NET?


Possible Duplicate:
How to Download A file stored in SQL DB in Binary Format

I stored some MS word docs in SQL Server. When I wanna download them, I save them as a file on server first then user can download them, but I'm looking for a way that doesn't involve saving the file to the server filesystem...


Solution

  • You'll need a custom HttpHandler implementing IHttpHandler. See IHttpHandler.ProcessRequest Method in MSDN. Set the appropriate MIME-type and redirect the binary data from your database to the HttpContext's OutputStream.

    An example (guessed, not tested) for a custom handler called Docs.ashx:

    using System.IO;
    using System.Web;
    
    public class Docs : IHttpHandler 
    {
        public void ProcessRequest (HttpContext context) 
        {
            context.Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            using (var streamReader = new StreamReader("fileSourceForDemonstration.docx"))
            {
                streamReader.BaseStream.CopyTo(context.Response.OutputStream);
            }
        }
    
        public bool IsReusable 
        {
            get { return false; }
        }
    }