简单的将图片上传到数据库
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.IO;
public partial class image : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected Int32 FileLength = 0;//记录文件长度变量
protected void Button1_Click(object sender, EventArgs e)
{
HttpPostedFile UpFile = FileUpload1.PostedFile;//HttpPostedFile 对象用于读取图像
FileLength = UpFile.ContentLength;//记录文件长度
try
{
if (FileLength == 0)
{
Label1.Text = "<b>请选择要上传的图片</b>";
return;
}
else
{
Byte[] Filebytearry = new Byte[FileLength];//图片临时存储
Stream Streamobject = UpFile.InputStream;//建立数据流
Streamobject.Read(Filebytearry, 0, FileLength);//读取图像文件数据,filebytearry为数据储存体,0为数据指针位置,filelength为数据长度
string sqlstr = ConfigurationManager.ConnectionStrings["ConnString"].ToString();
using (SqlConnection Con = new SqlConnection(sqlstr))
{
// SqlConnection Con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ToString());
string sqlcmd = "INSERT INTO tImage(ImageDate,ImageContentType,ImageDescriiption,ImageSize) values(@Image,@ImageContentType,@ImageDescriiption,@ImageSize)";
SqlCommand cmd = new SqlCommand(sqlcmd, Con);
//cmd.Parameters.Add("@ImageStore", SqlDbType.Int).Value = Session["ImageStore"].ToString();
cmd.Parameters.Add("@Image", SqlDbType.Binary, FileLength).Value = Filebytearry;//记录图片信息
cmd.Parameters.Add("@ImageContentType", SqlDbType.VarChar, 50).Value = UpFile.ContentType;//记录图片类型
cmd.Parameters.Add("@ImageDescriiption", SqlDbType.VarChar, 200).Value = TextBox1.Text;//记录图片说明信息
cmd.Parameters.Add("@ImageSize", SqlDbType.BigInt, 8).Value = UpFile.ContentLength; ;//记录图片长度
Con.Open();
cmd.ExecuteNonQuery();
Con.Close();
Label1.Text = "<b>成功上传<b>";
}
}
}
catch (Exception ex)
{
Label1.Text = ex.Message.ToString();
}
}
}