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, 0, 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为图片的读写,提供了很多方便之处吧!