该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
存入图片代码:
protected void btnUpload_Click(object sender, EventArgs e)
{
/*FileStream stream = new FileStream(@"E:\C#Exc\ImageToSQL\Image\huoying.jpg", FileMode.Open);
long FileSize = stream.Length;
byte[] getByte = new byte[(int)FileSize];
stream.Read(getByte, 0, (int)FileSize);*/
//获取数据
string getName = this.imgName.Text;
string getFile = this.FileUpload1.PostedFile.FileName;
string srt_URL = @"E:\C#Exc\ImageToSQL\Image\"+Path.GetFileName(this.FileUpload1.PostedFile.FileName);
//上传文件
//获取上传文件流
byte[] getByte = new byte[this.FileUpload1.PostedFile.ContentLength];
Stream fileStream = this.FileUpload1.PostedFile.InputStream;
//读入数据
fileStream.Read(getByte,0,this.FileUpload1.PostedFile.ContentLength);
//fileStream.Close();
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source = LENOVO-PC\\SQLEXPRESS;Initial Catalog = SQLEXC;User ID =sa;Password = 111111";
try
{
con.Open();
//读入数据
/*string strSql = "insert into StoreImage(imgName,imgContent,imgType,imgSize)values(@name,@content,@type,@size)";
SqlParameter[] pars = new SqlParameter[4];
pars[0] = new SqlParameter("@name", getName);
pars[1] = new SqlParameter("@content", getByte);
pars[3] = new SqlParameter("@type", this.FileUpload1.PostedFile.ContentType);
pars[4] = new SqlParameter("@size", this.FileUpload1.PostedFile.ContentLength);*/
SqlCommand cmd = new SqlCommand("insert into StoreImage(imgName,imgContent,imgType,imgSize,fileURL)values('" + getName + "','" + getByte + "','" + this.FileUpload1.PostedFile.ContentType + "','" + this.FileUpload1.PostedFile.ContentLength + "','" + srt_URL + "')", con);
int count = cmd.ExecuteNonQuery();
if (count == 1)
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "aler", "alert('图片记录成功添加到数据库');", true);
}
else
{
ScriptManager.RegisterStartupScript(this.Page,this.GetType(),"aler","alert('图片记录添加失败');",true);
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
读出图片代码:
protected void btnGetImg_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source = LENOVO-PC\\SQLEXPRESS;Initial Catalog = SQLEXC;User ID =sa;Password = 111111";
try
{
con.Open();
//ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "aler", "alert('step1');", true);
SqlCommand cmd = new SqlCommand("select * from StoreImage where id=1",con);
SqlDataReader dr = cmd.ExecuteReader();
//ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "aler", "alert('step2');", true);
if (dr.Read())
{
Response.ContentType = "image/jpeg";
Response.BinaryWrite((byte[])dr["imgContent"]);
//Response.ContentType = "image/jpeg";
//Response.OutputStream.Write(dr[2] as byte[], 0, Convert.ToInt32(dr[2].ToString()));
Response.End();
}
}
catch (Exception ex)
{
}
}