How to load a file stored in SQL DB in binary format

I just save the downloaded file to a binary field in SQL Server, but I also need to allow users to download it using Asp.NET. How can i do this?

Thanks in advance.

+5
source share
3 answers

Here's a Microsoft Knowledge Base article about this.

How to get a file from your database depends on the data access technology you use; I just assume that you have an array of bytes datacontaining a file (for example, by populating a DataSet and accessing a field) and some string filename.

Response.Clear()
Response.ContentType = "application/octet-stream"
Response.AddHeader("Content-Disposition", "attachment;filename=""" & filename & """")
Response.BinaryWrite(data)
Response.End()

download.aspx . , download.aspx, , .

+7

, , .

System.IO BinaryWriter filestream ... - :

FileStream fs = new FileStream("thisfile.bin", FileMode.Create);
binWriter= new BinaryWriter(fs);    

binWriter.Write(varHoldingSqlRetrievedBinaryData);
+3

(.ashx) -. ashx , ( PNG ) :

using System;
using System.Web;
using System.IO;

namespace ASHXTest
{
    public class GetLetter : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            // Get letter parameter from query string.
            string fileName = context.Request.MapPath(string.Format("{0}.png",
                context.Request.QueryString["letter"]));

            // Load file from disk/database/ether.
            FileStream stream = new FileStream(fileName, FileMode.Open,
                FileAccess.Read);
            byte[] buffer = new byte[stream.Length];
            stream.Read(buffer, 0, buffer.Length);
            stream.Close();

            // Write response headers and content.
            context.Response.ContentType = "image/png";
            context.Response.OutputStream.Write(buffer, 0, buffer.Length);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

Content-Disposition, :

context.Response.AddHeader("Content-Disposition",
    "attachment;filename=\"letter.png\"");
+2
source

All Articles