sqlServer中有一种数据类型是Image,用来存储图片大小不超过2g的图片,将图片转换为二进制!缺点是占用了很大的数据存储空间。但是现对于之前的存储物理路径来说读取图片和存储图片方便了很多。
那么图片在MVC程序中是如何存入数据库,并从数据库显示到页面上的呢:
下面是一个简单的小例子:
private string sqlconn = "Data Source=;Initial Catalog=Image;Persist Security Info=True;User ID=sa;Password=123456"; // // GET: /updownload/ public ActionResult Index() { return VIEw(); } [httpPost] [ValIDateinput(false)] public bool Upload(httpPostedfileBase[] fileToUpload) { string path = ""; try { //TODDO:读取任何地方的路径 foreach (httpPostedfileBase file in fileToUpload) { path = System.IO.Path.Combine(Server.MapPath("~/"),"uploadimage\" + System.IO.Path.Getfilename("00" + file.filename.Substring(file.filename.LastIndexOf(".")))); //写入数据库 file.SaveAs(path); //将需要存储的图片读取为数据流 fileStream fs = new fileStream(path,fileMode.Open,fileAccess.Read); Byte[] imgbtye = new byte[fs.Length]; fs.Read(imgbtye,Convert.ToInt32(fs.Length)); fs.Close(); using (sqlConnection conn = new sqlConnection(sqlconn)) { conn.open(); sqlCommand cmd = new sqlCommand(); cmd.Connection = conn; cmd.CommandText = "insert into T_TeacherImage(TeacherImage) values(@imgfile)"; sqlParameter par = new sqlParameter("@imgfile",sqlDbType.Image); par.Value = imgbtye; cmd.Parameters.Add(par); cmd.ExecuteNonquery(); } } return true; } catch { return false; } } #region 读取文件直接显示到视图上 public voID Read() { byte[] MyData = new byte[0]; using (sqlConnection conn = new sqlConnection(sqlconn)) { conn.open(); sqlCommand cmd = new sqlCommand(); cmd.Connection = conn; cmd.CommandText = "select TeacherImage from T_TeacherImage where ID='1'"; sqlDataReader sdr = cmd.ExecuteReader(); sdr.Read(); MyData = (byte[])sdr["TeacherImage"]; Response.ContentType = "image/gif"; Response.BinaryWrite(MyData); conn.Close(); } } #endregion那么图片又是如何显示到网页上的呢,很简单:
if (xhr.readyState == 4 && xhr.status == 200) { $('#personimg').attr("src","http://localhost:55576/updownload/Read"); }
这个demo的实现环境是MVC,图片的获取路径是,当前服务主机地址/controller/action
怎么样,sqlserver为图片的读写,提供了很多方便之处吧! 总结以上是内存溢出为你收集整理的被人忽视的sqlserver数据类型--image全部内容,希望文章能够帮你解决被人忽视的sqlserver数据类型--image所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)