上传文件到数据库
直接上代码:
前台:托一个asp.net上传控件和一个button按钮
后台代码:
protected void StartUpLoadFile(object sender, EventArgs e)
{
if (this.Fu_File.HasFile)
{
long fileLength = Fu_File.PostedFile.ContentLength;
byte[] bytes = new byte[fileLength];
Stream stream = Fu_File.PostedFile.InputStream;
stream.Read(bytes, 0, bytes.Length);
//Response.Write(bytes.Length + bytes.ToString());
//return;
InsertFileTable(bytes);
}
else
{
Response.Write("请先选择一个文件!");
}
}
private void InsertFileTable(byte[] bytes)
{
using (SqlConnection con = new SqlConnection("Data Source=.;Integrated Security=SSPI;Initial Catalog=DbExam10;"))
{
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO FileStreamTable (FileBytes) VALUES (@fileBytes)", con);
cmd.Parameters.Add("@fileBytes", SqlDbType.VarBinary).Value = bytes;
if (cmd.ExecuteNonQuery() != -1)
{
Response.Write("文件上传成功!");
}
}
}