数据库:sql server 2008 express
表:
CREATE TABLE [dbo].[filetest](
[id] [int] IDENTITY(1,1) NOT NULL,
[fs] [varbinary](max) NULL
) ON [PRIMARY]
写入:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection sconn =new SqlConnection("Server=192.168.1.11\\sqlexpress,1433; Database=DBCustomer; User Id=sa; Password=1234");
string FileName;
string FilePath = this.FileUpload1.PostedFile.FileName;
Stream FileStream = FileUpload1.PostedFile.InputStream;
FileName = Path.GetFileName(FilePath);
if (FileName != null && FileName != "")
{
int FileLen = FileUpload1.PostedFile.ContentLength;
byte[] FileData = new Byte[FileLen];
int n = FileStream.Read(FileData, 0, FileLen);
FileStream.Close();
SqlCommand com = new SqlCommand();
com.CommandText = "insert into filetest(fs) values(@fs)";
com.Parameters.Add(new System.Data.SqlClient.SqlParameter("@fs", System.Data.SqlDbType.Image, FileData.Length, "fs"));
com.Connection = sconn;
com.Parameters["@fs"].Value = FileData;
com.Connection.Open();
com.ExecuteNonQuery();
com.Connection.Close();
}
}
读取
SqlConnection sconn =new SqlConnection("Server=192.168.1.11\\sqlexpress,1433; Database=DBCustomer; User Id=sa; Password=1234");
//根据不同文件类型,设定ContentType 。
//Response.ContentType = "application/vnd.ms-excel";
//Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.ContentType = "application/pdf";
this.Response.Clear();
SqlCommand selcom = new SqlCommand();
selcom.CommandText = "select fs from filetest order by id desc";
selcom.Connection = sconn;
selcom.Connection.Open();
SqlDataReader dr = selcom.ExecuteReader();
dr.Read();
Byte[] b = new Byte[(dr.GetBytes(0, 0, null, 0, int.MaxValue))];
dr.GetBytes(0, 0, b, 0, b.Length);
dr.Close();
selcom.Connection.Close();
System.IO.Stream fs = this.Response.OutputStream;
fs.Write(b, 0, b.Length);
fs.Close();
this.Response.End();