Файловый поток SQL Server 2008 читается на веб-странице

У меня есть таблица SQL Server с включенным файловым потоком. Я могу загружать файлы сюда и обновлять. Как прочитать эти файлы на веб-странице .aspx? Файлы .pdf файлы.

С каждой строкой связаны 2 файла.

Я читаю строку на странице .aspx, и внизу я хочу, чтобы файлы открывались один под другим. Это для пользователя, чтобы распечатать строку с файлами.

Я проверил код, предложенный @dinglemeyer. Я хочу преобразовать свой PDF в изображение. Я предполагаю, что есть простой способ:

   <asp:GridView ID="gridview_f" runat="server" ShowHeaderWhenEmpty="false" PageSize="2" DataKeyNames="ID" DataSourceID="sql_files" AutoGenerateColumns="false" >
       <Columns>
           <asp:TemplateField Visible="false">
               <ItemTemplate>
                   <asp:Label ID="selID" runat="server" Text='<%# Bind("ID") %>' />
               </ItemTemplate>
           </asp:TemplateField>
           <asp:TemplateField>
               <ItemTemplate>
                   <asp:Label ID="selFname" runat="server" Text='<%# Bind("filename") %>' />
                   <br />
                   <asp:image ID="selFile" runat="server" ImageUrl='<%# "Handler.ashx?id="+Eval("ID") %>' />
               </ItemTemplate>
           </asp:TemplateField>
       </Columns>
   </asp:GridView>


   // code behind for ginfing the grid as the parentId is extracted from other form values.
    private void gridView_Data(string id)
           {
               sql_files.SelectCommand = "SELECT ID, filename from myFILESTABLE where PARENTID=" + id;
    }


    // Handler.ascx
          public void ProcessRequest(HttpContext context)
        {

            SqlConnection conn = null;
            SqlCommand cmd = null;
            SqlDataReader sdr = null;

            conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["my_dbconn"].ConnectionString);
            try
            {
                    cmd = new SqlCommand("SELECT filecontent from myFILESTABLE WHERE ID=" + context.Request.QueryString["ID"], conn);
                conn.Open();
                sdr = cmd.ExecuteReader();
                while (sdr.Read())
                {
                    context.Response.ContentType = "content/pdf";
                    context.Response.BinaryWrite((byte[])sdr["filecontent"]);
                }
                sdr.Close();
            }
            finally
            {
                conn.Close();
            }

person user3285061    schedule 08.01.2016    source источник
comment
Если вы опубликуете соответствующий раздел кода того, что вы пробовали, этот вопрос будет получен гораздо лучше.   -  person Kevin    schedule 09.01.2016
comment
Я могу писать/обновлять файл, но не могу читать как pdf. Мой SQL: выберите fileContent из tblFiles, где ID=? Я получаю данные в TSql. У меня может быть gridview с fileContent в качестве данных, но я застрял при его заполнении.   -  person user3285061    schedule 09.01.2016
comment
Я имею в виду, что вы должны добавить блок кода с подробным описанием того, что у вас есть в вашем ответе, отредактировав его в   -  person Kevin    schedule 09.01.2016


Ответы (1)


Мои извинения за задержку ответа. Из ссылки: http://weblogs.asp.net/aghausman/saving-and-retrieving-file-using-filestream-sql-server-2008 Вот мой рабочий код:

   <asp:GridView ID="mygrid1" runat="server" AutoGenerateColumns="false" DataKeyNames="ID" DataSourceID="sql_file" OnRowCommand="gridview_f_RowCommand"  GridLines="None" >
       <Columns>
           <asp:TemplateField HeaderText="S.No">
               <ItemTemplate>
                   <asp:Label ID="Label12" runat="server" Text='<%#  Container.DataItemIndex + 1 %>'  />
               </ItemTemplate>
           </asp:TemplateField>
           <asp:TemplateField HeaderText="Attachments" >
               <ItemTemplate>
                   <asp:Label ID="Label11" runat="server" Text='<%# Bind("ID") %>' Visible="false" />
                   <asp:LinkButton ID="lLabel12" runat="server" Text='<%# Bind("myFileName") %>' CommandName="GetFile" CommandArgument='<%#Eval("ID") + "|" + Eval("myFileName") %>'>                           
                   </asp:LinkButton>
               </ItemTemplate>
           </asp:TemplateField>
       </Columns>
   </asp:GridView>

" >

Код позади:

     protected void gridview_f_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName=="GetFile")
        {
            string[] ca = e.CommandArgument.ToString().Split('|');
            SqlConnection objSqlCon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myConn"].ConnectionString);
            objSqlCon.Open();
            SqlTransaction objSqlTran = objSqlCon.BeginTransaction();

            SqlCommand objSqlCmd = new SqlCommand("spGet_getMyFile", objSqlCon, objSqlTran);
            objSqlCmd.CommandType = CommandType.StoredProcedure;

            SqlParameter objSqlParam1 = new SqlParameter("@ID", SqlDbType.VarChar);
            objSqlParam1.Value = ca[0]; // e.CommandArgument;

            objSqlCmd.Parameters.Add(objSqlParam1);

            string path = string.Empty;
            using (SqlDataReader sdr = objSqlCmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    path = sdr[0].ToString();
                }
            }

            objSqlCmd = new SqlCommand("SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()", objSqlCon, objSqlTran);

            byte[] objContext = (byte[])objSqlCmd.ExecuteScalar();

            SqlFileStream objSqlFileStream = new SqlFileStream(path, objContext, FileAccess.Read);

            byte[] buffer = new byte[(int)objSqlFileStream.Length];
            objSqlFileStream.Read(buffer, 0, buffer.Length);
            objSqlFileStream.Close();
            objSqlTran.Commit();
            Response.AddHeader("Content-disposition", "attachment; filename=" + ca[1]);
            Response.ContentType = "application/pdf";

            Response.BinaryWrite(buffer);


        }
    }

Хранимая процедура SpGet_getMyfile:

СОЗДАТЬ ПРОЦЕДУРУ [dbo].[spGet_getMyFile] ( @id BIGINT )

AS

SELECT   filestreamColumn.PathName()
   FROM dbo.TableThatHasTheFileStream
      WHERE Id=@id
person user3285061    schedule 19.01.2016