转:http://topic.csdn.net/t/20030918/17/2275535.html
1 楼acewang(龍芯*Inside!)
在SQL Server中保存和输出任意类型的文件
我们可以把任意类型的文件保存到SQL Server中,在进行例子之前,先建立测试用表,TestFile.sql:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[TestFiles]')
and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[TestFiles]
GO
CREATE TABLE [dbo].[TestFiles] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[MyFileName] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[FileType] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[MyFile] [image] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
下面创建上传表单:
一旦提交了表单,我们使用HtmlInputFile类的PostedFile属性来访问我们上载的文件,用HttpPostedFile类的属性和方法来进行读取、保存上载文件和得到上载文件的其它信息。这里我们不使用SaveAs方法,因为它是用来保存文件的。我们要把数据保存到数据库中,我们使用InputStream属性,它用来初始化流来读取我们的数据。同时,我们使用ContentLength来读取文件大小,ContentType读取文件类型。然后创建byte数组,把文件流保存进该数组,然后保存到数据库即可。
下面就是完整的代码【CS版本】UploadFile.aspx:
<% @Page Language="C#" %>
<% @Import Namespace="System.IO" %>
<% @ Import Namespace="System.Data" %>
<% @ Import Namespace="System.Data.SqlClient" %>
<script runat="server">
public void UploadBtn_Click (Object sender, EventArgs e){
//得到提交的文件
Stream fileDataStream = MyFile.PostedFile.InputStream;
//得到文件大小
int fileLength = MyFile.PostedFile.ContentLength;
//创建数组
byte[] fileData = new byte[fileLength];
//把文件流填充到数组
fileDataStream.Read(fileData,0,fileLength);
//得到文件名字
string fileTitle = MyFileName.Value;
//得到文件类型
string fileType = MyFile.PostedFile.ContentType;
//构建数据库连接,SQL语句,创建参数
SqlConnection connection = new SqlConnection("Server=.;uid=sa;pwd=;Database=TestUploadFile");
SqlCommand command = new SqlCommand ("INSERT INTO TestFiles (MyFileName,MyFile,FileType)" +
"VALUES (@MyFileName,@MyFile,@FileType)", connection);
SqlParameter paramTitle = new SqlParameter ("@MyFileName", SqlDbType.VarChar,35);
paramTitle.Value = fileTitle;
command.Parameters.Add(paramTitle);
SqlParameter paramData = new SqlParameter ("@MyFile", SqlDbType.Image);
paramData.Value = fileData;
command.Parameters.Add(paramData);
SqlParameter paramType = new SqlParameter ("@FileType", SqlDbType.VarChar,25);
paramType.Value = fileType;
command.Parameters.Add(paramType);
//打开连接,执行查询
connection.Open();
command.ExecuteNonQuery();
connection.Close();
Message.Text="你的文件已经成功上载";
MyFileName.Value = "";
}
</script>
<hr>
<asp:label id="Message" Text="选择文件和文件名字:" runat="server"/>
<hr>
<form method="post" enctype="multipart/form-data" runat="server">
<b>文件名字:</b><input id="MyFileName" type="text" runat="server">
<P>
<b>文件:</b><input id="MyFile" type="file" runat="server">
<br><br>
<input type=submit value="开始上传" OnServerclick="UploadBtn_Click" runat="server">
</form>
一旦我们上载成功,我们可以对文件进行浏览:只需要设置页面的MIME类型,然后用Response对象的BinaryWrite()进行输出。
ShowUploadFile.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=.;uid=sa;pwd=;Database=TestUploadFile");
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-Size="9" HorizontalAlign="Center"/>
<Columns>
<asp:TemplateColumn HeaderText="文件名字">
<ItemTemplate>
<b>
<%# DataBinder.Eval(Container.DataItem, "MyFileName") %>
</b>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="类型">
<ItemTemplate>
<b>
<%# DataBinder.Eval(Container.DataItem, "FileType") %>
</b>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="查看">
<ItemTemplate>
<b>
<a href="ShowFile.aspx?ID=<%# DataBinder.Eval(Container.DataItem, "ID") %>">查看文件</a>
</b>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
</form>
ShowFile.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 WHERE ID = '" + Request.QueryString["ID"] + "'";
SqlConnection connection = new SqlConnection("Server=.;uid=sa;pwd=;Database=TestUploadFile");
SqlCommand command = new SqlCommand(sql, connection);
connection.Open();
SqlDataReader dr = command.ExecuteReader();
if(dr.Read()){
Response.Clear();
Response.AddHeader("Content-Type",dr["FileType"].ToString());
Response.AddHeader("Content-Disposition", "attachment;filename=" +
dr["FileName"].ToString() + ";");
Response.BinaryWrite((byte[])dr["MyFile"]);
}
dr.Close();
connection.Close();
}
</script>
1 楼acewang(龍芯*Inside!)
在SQL Server中保存和输出任意类型的文件
我们可以把任意类型的文件保存到SQL Server中,在进行例子之前,先建立测试用表,TestFile.sql:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[TestFiles]')
and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[TestFiles]
GO
CREATE TABLE [dbo].[TestFiles] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[MyFileName] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[FileType] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[MyFile] [image] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
下面创建上传表单:
一旦提交了表单,我们使用HtmlInputFile类的PostedFile属性来访问我们上载的文件,用HttpPostedFile类的属性和方法来进行读取、保存上载文件和得到上载文件的其它信息。这里我们不使用SaveAs方法,因为它是用来保存文件的。我们要把数据保存到数据库中,我们使用InputStream属性,它用来初始化流来读取我们的数据。同时,我们使用ContentLength来读取文件大小,ContentType读取文件类型。然后创建byte数组,把文件流保存进该数组,然后保存到数据库即可。
下面就是完整的代码【CS版本】UploadFile.aspx:
<% @Page Language="C#" %>
<% @Import Namespace="System.IO" %>
<% @ Import Namespace="System.Data" %>
<% @ Import Namespace="System.Data.SqlClient" %>
<script runat="server">
public void UploadBtn_Click (Object sender, EventArgs e){
//得到提交的文件
Stream fileDataStream = MyFile.PostedFile.InputStream;
//得到文件大小
int fileLength = MyFile.PostedFile.ContentLength;
//创建数组
byte[] fileData = new byte[fileLength];
//把文件流填充到数组
fileDataStream.Read(fileData,0,fileLength);
//得到文件名字
string fileTitle = MyFileName.Value;
//得到文件类型
string fileType = MyFile.PostedFile.ContentType;
//构建数据库连接,SQL语句,创建参数
SqlConnection connection = new SqlConnection("Server=.;uid=sa;pwd=;Database=TestUploadFile");
SqlCommand command = new SqlCommand ("INSERT INTO TestFiles (MyFileName,MyFile,FileType)" +
"VALUES (@MyFileName,@MyFile,@FileType)", connection);
SqlParameter paramTitle = new SqlParameter ("@MyFileName", SqlDbType.VarChar,35);
paramTitle.Value = fileTitle;
command.Parameters.Add(paramTitle);
SqlParameter paramData = new SqlParameter ("@MyFile", SqlDbType.Image);
paramData.Value = fileData;
command.Parameters.Add(paramData);
SqlParameter paramType = new SqlParameter ("@FileType", SqlDbType.VarChar,25);
paramType.Value = fileType;
command.Parameters.Add(paramType);
//打开连接,执行查询
connection.Open();
command.ExecuteNonQuery();
connection.Close();
MyFileName.Value = "";
}
</script>
<hr>
<asp:label id="Message" Text="选择文件和文件名字:" runat="server"/>
<hr>
<form method="post" enctype="multipart/form-data" runat="server">
<b>文件名字:</b><input id="MyFileName" type="text" runat="server">
<P>
<b>文件:</b><input id="MyFile" type="file" runat="server">
<br><br>
<input type=submit value="开始上传" OnServerclick="UploadBtn_Click" runat="server">
</form>
一旦我们上载成功,我们可以对文件进行浏览:只需要设置页面的MIME类型,然后用Response对象的BinaryWrite()进行输出。
ShowUploadFile.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=.;uid=sa;pwd=;Database=TestUploadFile");
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-Size="9" HorizontalAlign="Center"/>
<Columns>
<asp:TemplateColumn HeaderText="文件名字">
<ItemTemplate>
<b>
<%# DataBinder.Eval(Container.DataItem, "MyFileName") %>
</b>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="类型">
<ItemTemplate>
<b>
<%# DataBinder.Eval(Container.DataItem, "FileType") %>
</b>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="查看">
<ItemTemplate>
<b>
<a href="ShowFile.aspx?ID=<%# DataBinder.Eval(Container.DataItem, "ID") %>">查看文件</a>
</b>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
</form>
ShowFile.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 WHERE ID = '" + Request.QueryString["ID"] + "'";
SqlConnection connection = new SqlConnection("Server=.;uid=sa;pwd=;Database=TestUploadFile");
SqlCommand command = new SqlCommand(sql, connection);
connection.Open();
SqlDataReader dr = command.ExecuteReader();
if(dr.Read()){
Response.Clear();
Response.AddHeader("Content-Type",dr["FileType"].ToString());
Response.AddHeader("Content-Disposition", "attachment;filename=" +
dr["FileName"].ToString() + ";");
Response.BinaryWrite((byte[])dr["MyFile"]);
}
dr.Close();
connection.Close();
}
</script>