026. asp.net中将图片以二进制方式保存到数据库并以HTTP流方式输出
保存到数据库中
protected void imgbtnCreate_Click(object sender, ImageClickEventArgs e) { string PerHomeName=tbPerHomeName.Text;//获取空间名 string PerHomeSign=txtPerSign.Text; //获取个性签名 string imgPath = uploadFile.PostedFile.FileName;//获取文件件名 string lastName = imgPath.Substring(imgPath.LastIndexOf(".") + 1);//获取文件上传后缀名 SqlConnection conn = new SqlConnection( "server=.;database=TYW;uid=sa;pwd=123.456;"); conn.Open(); if (uploadFile.PostedFile.FileName != "" && lastName.ToLower() == "jpg" || lastName.ToLower() == "gif") { if (uploadFile.PostedFile.ContentLength > 40960) { Response.Write("<script language='javaScript'>alert('你上传的图片超过了40KB!')</script>"); return; } int imgLength = uploadFile.PostedFile.ContentLength;//获取上传文件大小 Byte[] imageData = new Byte[imgLength]; //定义Byte数组 HttpPostedFile hp = uploadFile.PostedFile;//创建访问客户端上传文件的对象 Stream imagestream = hp.InputStream;//创建数据流对象 //将图片数据放到image数据对象实例中,其中0代表数组指针的起始位置,imagelength表示要读取流的长度 imagestream.Read(imageData, 0, imgLength); string sqlstr = "insert into card(cardNo,cardBound,email)values('" + 1234 + "','" + 9966770 + "',@ImageData)"; SqlCommand comm = new SqlCommand(sqlstr, conn); comm.Parameters.Add("@ImageData", SqlDbType.Image); comm.Parameters["@ImageData"].Value = imageData; comm.ExecuteNonQuery(); conn.Close(); Response.Write("<Script>alert('个人空间创建成功!')</Script>"); } else { Response.Write("<script>alert('上传头像不能为空,且格式必须为gif或jpg!');location='javascript:history.go(-1)'</script>"); } }
以HTTP流形式输出到界面:
protected void Page_Load(object sender, EventArgs e) { string requestID = Request.QueryString["id"];//获取Default.aspx页面传过来的id值 SqlConnection conn = new SqlConnection("server=.;database=TYW;uid=sa;pwd=123.456;"); string strsql = "select * from [card] where cardBound=" + 9966770; SqlCommand comm = new SqlCommand(strsql, conn);//创建命令对象 conn.Open(); SqlDataReader dr = comm.ExecuteReader();//创建数据阅读器 if (dr.HasRows) { while (dr.Read()) { byte[] imageData = (byte[])dr["email"]; Response.BinaryWrite(imageData);//输出二进制流形式的图片 } } dr.Close(); conn.Close(); }