<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
private string connectionString = "Data Source=192.168.3.1;Initial Catalog=TestData;User Id=sa;Password=lambada;";
protected void Button1_Click(object sender, EventArgs e)
{
//得到文件数组
byte[] fileData = FileUpload1.FileBytes;
//得到文件名字
string fileName = System.IO.Path.GetFileName(FileUpload1.FileName);
//得到文件类型
string fileType = FileUpload1.PostedFile.ContentType;
//构建数据库连接,SQL语句,创建参数
System.Data.SqlClient.SqlConnection myConnection
= new System.Data.SqlClient.SqlConnection(connectionString
);
String strSql = "INSERT INTO FileTable (ContentType,Content,Title)" +
"VALUES (@ContentType,@Content,@Title)";
System.Data.SqlClient.SqlCommand command
= new System.Data.SqlClient.SqlCommand(strSql, myConnection
);
command.Parameters.AddWithValue("@ContentType", fileType);
command.Parameters.AddWithValue("@Content", fileData);
command.Parameters.AddWithValue("@Title", fileName);
//打开连接,执行查询
myConnection.Open();
command.ExecuteNonQuery();
myConnection.Close();
myConnection.Dispose();
Response.Redirect(Request.FilePath);
}
protected void Page_Load(object sender, EventArgs e)
{
/*
CREATE TABLE [FileTable] (
[FileId] [int] IDENTITY (1, 1) NOT NULL ,
[Title] [nvarchar] (255) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[ContentType] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[Content] [image] NULL ,
CONSTRAINT [PK_FileTable] PRIMARY KEY CLUSTERED
(
[FileId]
) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
*/
//构建数据库连接,SQL语句,创建参数
System.Data.SqlClient.SqlConnection myConnection
= new System.Data.SqlClient.SqlConnection(connectionString
);
String strSql = "select * from FileTable";
System.Data.SqlClient.SqlCommand command
= new System.Data.SqlClient.SqlCommand(strSql, myConnection
);
//打开连接,执行查询
myConnection.Open();
System.Data.SqlClient.SqlDataReader dr = command.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
myConnection.Close();
myConnection.Dispose();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="上传文件" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="FileId" HeaderText="文件名" DataTextField="Title" DataNavigateUrlFormatString="~/Download.ashx?FileId={0}" />
</Columns>
</asp:GridView>
</form>
</body>
</html>
//csharp/6768