How to read binary data from SQL Server and display in browser

I have binary data in my SQL Server, I want to read that binary data and display in browser as this binary data is a PDF file - how can this be done?

Here is my database structure:

database

I am retrieving other data from database successfully as shown in this screenshot:

data

What I want is when user click on view button, binary data from database should read and display new webview

        <ListView.ItemTemplate>

            <DataTemplate>
                <ViewCell>
                    <StackLayout Orientation="Horizontal" Padding="12,6">

                    <Label Text="{Binding ReportName}" FontSize="24" 
               Style="{DynamicResource ListItemTextStyle}" />

                    <Label Text="{Binding Date}"  FontSize="18" Opacity="0.6"
               Style="{DynamicResource ListItemDetailTextStyle}"/>

                    <Button Clicked="ShowPDF" Text="View" CommandParameter="{Binding FileContent}"></Button>
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>

    </ListView>

1 answer

  • answered 2018-04-17 04:21 Abdul Rehman Zafar

    You first need to retrieve the binary data and content type from the database ,for which you can either use ado.net or entity framework which ever you prefer, then you can convert that binary data to your preferred format and return the web view

             byte[] bytes;
            string contenttype;
    
            string connectionstring = @"Data Source=localhost\SQLEXPRESS;" + "Initial Catalog=foo_database; Integrated Security=SSPI";
    
            SqlConnection myconnection = new SqlConnection();
    
            myconnection.ConnectionString = connectionstring;
    
            string cvsql = "select binarydata,contenttype from customer where customer_id='1'";
    
            SqlCommand mycommand = new SqlCommand(cvsql, myconnection);
    
            SqlDataReader myreader;
    
            try
            {
                myconnection.Open();
                myreader = mycommand.ExecuteReader();
    
                myreader.Read();
    
                bytes = (byte[])myreader["binarydata"];
                contenttype = myreader["contenttype "].ToString();
    
                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "";
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.ContentType = contenttype;
                //Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
                Response.BinaryWrite(bytes);
                Response.Flush();
                Response.End();
       }
    
       catch{
    
       }