How can I reading binary data and display in in the web browser?

I'm trying to display a Word or PDF file in my web page by retrieving it from the SQL server.  I created the webpage with Visual Studio with c# code behind.  How can I retrieve this file?
//my datagrid has query string to use a .ashx file to retreive the file.

<asp:ImageField 
                        HeaderText="File" 
                        DataImageUrlFormatString="ViewImage.ashx?id={0}"
                        DataImageUrlField="AppFilesId">
                        </asp:ImageField>

//I'm using this file to flush out the data.

using System;
using System.Web;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
using System.Data;

public class viewimage : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        HttpRequest request = context.Request;
        HttpResponse response = context.Response;
        //get the ID of the upload record
        //being careful to make sure that the
        //querystring 'id' is not null ...

        int uploadid;
        string queryString = request.QueryString["id"];

        if (string.IsNullOrEmpty(queryString)
            || !(int.TryParse(queryString, out uploadid)))
            return;
        //...and the proper data type

        //create our connection
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["JobPostingsConnectionString"].ConnectionString))
        {
            //create our command
            SqlCommand cmd = new SqlCommand(@"SELECT AppFiles.FileId,AppFiles.AppFilesId,AppFiles.ResumeFileSize,AppFiles.ResumeFileType,AppFiles.ResumeContent,Apps.FileID WHERE AppFiles.AppFilesId=@AppFilesId", conn);
            
            //add our parameter
            cmd.Parameters.AddWithValue("@AppFilesId", uploadid);

            //open the connection
            conn.Open();

            //create a sql datareader to read only one row of data
            SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow);
            if (reader.HasRows)
            {
                reader.Read();

                //set the content type to the stored content type in the DB
                String ContentType = reader["ResumeFileType"].ToString();

                //set the content length to the stored content length in the DB
                String ContentLength = reader["ResumeFileSize"].ToString();

                //read out the binary data from the db
                byte[] data = reader["ResumeContent"] as byte[];

                //set the response headers for the file
                //so the browser can render it properly
                response.ContentType = ContentType;
                response.AddHeader("ResumeFileSize", ContentLength);

                //write out the data to the outputstream
                BinaryWriter bw = new BinaryWriter(response.OutputStream);
                bw.Write(data, 0, data.Length);
                bw.Close();
            }
        }
    }

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

Open in new window

need_codeAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Daniel JungesCommented:
you can not display it directly, if youwant to display it in an human readable form the either you convert the file to html first and then redirect the generated file or you let the user download the file
0
DaveKeyesCommented:
This is how I do it, we store our documents in Sharepoint, and retrieve the binary data from there when ever a user clicks on a link to the document:

        public ActionResult Index(string id)
            {
            try
                {
                if (id.Length > 5)
                    {
                    string strPassword = WebConfigurationManager.AppSettings["xxxxxxxx"].ToString();

                    PortDocLib docLib = new PortDocLib(strPassword,
                                                                               "http://intranet/sites/somesite",
                                                                               null);

                    docLib.SpCredentials = new NetworkCredential("sharepoint", strPassword, "your domain");

                        // Be sure to set the MIME

                    this.HttpContext.Response.ContentType = "application/msword";

                        // This will display the Word document in Word, the user must have MS Word installed.

                    this.HttpContext.Response.BinaryWrite(docLib.GetFile(id));
                    return (null);
                    }
                else
                    {
                    return (View());
                    }
                }

            catch (Exception exp)
                {
                string strError;

                strError = String.Format("{0} {1} {2}",
                                         "Index",
                                         "experienced an error: ",
                                         exp.Message);

                Logger.WriteLog(ELogLevel.ERROR, strError);
                throw new ApplicationException(strError);
                }

            finally
                {
                }
            }
0
need_codeAuthor Commented:
This worked for me.

<%@ WebHandler Language="C#" Class="FileStream" %>
using System;
using System.Web;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

/// <summary>
/// Reponsible for flushing out the file from the database to the user.
/// </summary>
public class FileStream : IHttpHandler
{
    public void ProcessRequest (HttpContext context)
    {
       //get the file id
     
        int fileId = int.Parse(context.Request.QueryString["FileId"]);
     
     using (SqlCommand command = new SqlCommand())
     {
         // get the file from database
         command.Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["PostingsConnectionString"].ConnectionString);
         command.CommandText = "select * from [AppFiles] where FileId = @FileId";
         command.Parameters.Add("@FileId", SqlDbType.Int).Value = fileId;
         command.Connection.Open();
         SqlDataReader reader = command.ExecuteReader();
         if (reader.Read())
        {
            // flush out the binary data to the user
            context.Response.Clear();
            context.Response.ContentType = (string)reader["ResumeFileType"];
            context.Response.AddHeader("Content-Disposition", String.Format("inline;ResumeFileName={0};", reader["ResumeFileName"].ToString()));
            context.Response.AddHeader("Content-Length", reader["ResumeFileSize"].ToString());
            context.Response.BinaryWrite((byte[])reader["ResumeContent"]);
            context.Response.End();          
        }
      }
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.