-1

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...

Community
  • 1
  • 1
ePezhman
  • 4,010
  • 7
  • 44
  • 80
  • You could put the data directly in the response from the Web server. – Johann Blais Oct 11 '11 at 12:20
  • 1
    Your title is different from your question. What are you actually asking? – James Oct 11 '11 at 12:21
  • @James - I don't really see a mismatch between the two? They are asking how to stream binary data held in SQL Server without the intermediate step of saving to the file system first. – Martin Smith Oct 11 '11 at 12:28

1 Answers1

2

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; }
    }
}
Oli
  • 830
  • 7
  • 20
  • 1
    Although you could do it that way you could do it just as well with a single .aspx page taking a querystring parameter of some sort. The code will be much the same either way though. – Chris Oct 11 '11 at 12:27
  • @Chris The answer to [this question](http://stackoverflow.com/questions/1030433/byte-serving-pdfs-from-sql-varbinary) seems to solve it the .aspx-way. Answered by another Chris :-) – Oli Oct 11 '11 at 12:48