从数据库中读取文件

<h3>从数据库中读取文件</h3>
            输入文件在数据库中的ID:
            
<asp:textbox id="FileIDTextBox" runat="server"></asp:textbox>
            
<asp:button id="SubmitBtn" runat="server" Text="显示" OnClick="SubmitBtn_Click"></asp:button>

            void SubmitBtn_Click(object sender, System.EventArgs e)
            
{
                
int FileID = Convert.ToInt32(FileIDTextBox.Text);

                
string ConnStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer"];
                
string query = "SELECT * FROM FileTable WHERE FileID = @FileID";

                SqlCommand myCommand 
= new SqlCommand(query, new SqlConnection(ConnStr));
                myCommand.Parameters.Add(
"@FileID", SqlDbType.Int);
                myCommand.Parameters[
"@FileID"].Value = FileID;
                myCommand.Connection.Open();

                SqlDataReader dr 
= myCommand.ExecuteReader();

                
if(dr.Read())
                
{
                         Response.AddHeader("content-disposition","inline;filename=文件名.后缀名");
                    Response.ContentType 
= (string)dr["FileContentType"];//Response.ContentType = "byte[]";
                    Response.OutputStream.Write((
byte[])dr["FileData"], 0, (int)dr["FileSize"]);
                       //Response.BinaryWrite((byte[])dr["FileData"]);
                }

                
else
                
{
                    Response.Write(
"没有这个文件的ID号");
                    Response.End();
                }


                dr.Close();
                myCommand.Connection.Close();
            }
posted @ 2006-06-09 13:01  Tim工作室  阅读(600)  评论(0编辑  收藏  举报