如何从SQL Server读取二进制数据并在浏览器中显示

时间:2018-04-17 04:21:16

标签: c# xamarin xamarin.forms

我的SQL Server中有二进制数据,我想读取二进制数据并在浏览器中显示,因为这个二进制数据是PDF文件 - 如何做到这一点?

这是我的数据库结构:

database

我正在从数据库中成功检索其他数据,如此屏幕截图所示:

data

我想要的是当用户点击查看按钮时,数据库中的二进制数据应该读取并显示新的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 个答案:

答案 0 :(得分:1)

首先需要从数据库中检索二进制数据和内容类型,您可以使用自己喜欢的ado.net或实体框架,然后将二进制数据转换为首选格式并返回Web图

         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{

   }