Please make sure that you have read the article Using Images
and Files with SQL Server: Part 1 as this article builds upon the
previous example.
Once you've uploaded data into SQL Server, you can easily retrieve the
content and allow the viewer to see the images and files made available in
your database. You just have to access and then set the MIME type of the
page displaying the information and then use the Response object's
BinaryWriter method.
Before looking at the code for that though, here's some simple code for
listing the files from your database (setup in Part1). Call it
get_files_list.aspx
<% @Page Language="C#" %>
<% @Import Namespace="System.IO" %>
<% @ Import Namespace="System.Data" %>
<% @ Import Namespace="System.Data.SqlClient" %>
<script runat="server">
private void Page_Load(Object sender, EventArgs e) {
string sql="SELECT * FROM TestFiles";
SqlConnection connection = new SqlConnection("server=localhost; uid=; pwd=; Database=mydb");
SqlCommand command = new SqlCommand(sql, connection);
connection.Open();
FileList.DataSource = command.ExecuteReader();
FileList.DataBind();
connection.Close();
}
</script>
<form runat="server">
<asp:DataGrid id="FileList" runat="server"
BorderColor="orange"
BorderWidth="2"
CellPadding="4"
AutoGenerateColumns="false"
ShowHeader="true"
Align="center">
<HeaderStyle BorderColor="White" BackColor="black"
ForeColor="White"
Font-Bold="True"
Font-Name="Arial"
Font-Size="9" HorizontalAlign="Center"/>
<Columns>
<asp:TemplateColumn HeaderText="File Name">
<ItemTemplate>
<b>
<font face="arial" size="2">
<%# DataBinder.Eval(Container.DataItem, "MyFileName") %>
</b>
</font>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="File Type">
<ItemTemplate>
<b>
<font face="arial" size="2">
<%# DataBinder.Eval(Container.DataItem, "FileType") %>
</b>
</font>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Action">
<ItemTemplate>
<b>
<font face="arial" size="2">
<a href="get_files.aspx?ID=<%# DataBinder.Eval(Container.DataItem, "ID") %>">
View File</a>
</b>
</font>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
</form>
|
This will display a datagrid with the File Name, Type, and a link to
view the file. When clicked it will go to the page get_files.aspx
which will grab the ID passed in the querystring, and then display the
file.