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