Link to home
Start Free TrialLog in
Avatar of need_code
need_codeFlag for United States of America

asked on

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

Avatar of Daniel Junges
Daniel Junges
Flag of Brazil image

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
Avatar of Member_2_2459312
Member_2_2459312

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
                {
                }
            }
ASKER CERTIFIED SOLUTION
Avatar of need_code
need_code
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial