(转载)数据库存取图片并在MVC3中显示在View中
2015-01-15 14:41
381 查看
简介:在有些情况下需要将图片转换为二进制流存放在数据库中,当显示时再从数据库中读出来显示在界面上。
本文简单介绍数据库中图片的存取方法,并在MVC3中显示在Razor视图中。仅供初学者参考学习。
1. 将图片转换为二进制流
/// <summary>
/// convert a picture file to byte array
/// </summary>
public byte[] GetBytesFromImage(string filename)
{
FileStream fs = new FileStream(filename,FileMode.Open,FileAccess.Read);
int length = (int)fs.Length;
byte[] image = new byte[length];
fs.Read(image, 0, length);
fs.Close();
return image;
}
2. 将二进制文件写入数据库
/// <summary>
/// write byte array to database
/// </summary>
public void StoreImageToDB(byte[] image)
{
string connectionString = "Data Source=.;Initial Catalog=MyDB;User Id=sa;Password=123456";
string strSql = "INSERT INTO TestImage(image) Values(@image)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(strSql,connection);
cmd.Parameters.Add("@image", SqlDbType.Image).Value = image;
connection.Open();
cmd.ExecuteNonQuery();
cmd.Clone();
}
}
3. 从数据库中读取图片
/// <summary>
/// get image from database
/// </summary>
public byte[] GetBytesFromDB()
{
string connectionString = "Data Source=.;Initial Catalog=MyDB;User Id=sa;Password=123456";
string strSql = "SELECT top 1 image FROM TestImage";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(strSql,connection);
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
byte[] temp = null;
if (reader.Read())
{
temp = (byte[])reader.GetValue(0);
}
return temp;
}
}
4. 在Controller中添加返回图片的方法
/// <summary>
/// Action that return the image file
/// </summary>
public FileResult Image()
{
//get image from database
byte[] image = GetBytesFromDB();
//return the image to View
return new FileContentResult(image, "image/jpeg");
//or like below
//MemoryStream mem = new MemoryStream(image, 0, image.Length);
//return new FileStreamResult(mem, "image/jpg");
}
5. 在View中显示图片, 将src指定为我们返回图片的Action方法
<img alt="" src="/Home/Image" />
上面的方法都是我们自己实现且用SQL语句存取数据库,其实.NET框架已经给我们封装好了
很多现成的类,再加上 EF 存取数据库可以使我们的代码变得更加 elegant。
1. 前台上传图片
@using (Html.BeginForm("Edit", "Admin", FormMethod.Post,
new { enctype = "multipart/form-data" })) {
<div>Upload new image: <input type="file" name="Image" /></div>
<input type="submit" value="Save" />
}
它相当于 webform 中的 :
<form action="/Admin/Edit" enctype="multipart/form-data" method="post">
enctype = "multipart/form-data" 告诉浏览器将我们的文件流 post 到后台。
2. 将图片存入数据库
[HttpPost]
public ActionResult Edit(Product product, HttpPostedFileBase image) {
if (ModelState.IsValid) {
if (image != null) {
product.ImageMimeType = image.ContentType;
product.ImageData = new byte[image.ContentLength];
image.InputStream.Read(product.ImageData, 0, image.ContentLength);
}
// save the product
repository.SaveProduct(product);
return RedirectToAction("Index");
} else {
// there is something wrong with the data values
return View(product);
}
}
MVC框架会自动封装实例化我们的实体类和文件流并传到 post 方法中。
其中 HttpPostedFileBase 是一个抽象类,实际传过来的对象
是它的子类 HttpPostedFileWrapper 对象。
HttpPostedFileBase 类定义了很多操作文件流的属性和接口。
3. 在 view 中请求显示图片的 action
<img src="@Url.Action("GetImage", "Product", new { Model.ProductID })" />
其中读取图片流的方法如下:
public FileContentResult GetImage(int productId) {
Product prod = repository.Products.FirstOrDefault(p => p.ProductID == productId);
if (prod != null) {
return File(prod.ImageData, prod.ImageMimeType);
} else {
return null;
}
}
其中 FileContentResult 是 ActionResult 的子类 ,action 的返回类型有很多种,它们都继承自抽象类 ActionResult 。
本文简单介绍数据库中图片的存取方法,并在MVC3中显示在Razor视图中。仅供初学者参考学习。
1. 将图片转换为二进制流
/// <summary>
/// convert a picture file to byte array
/// </summary>
public byte[] GetBytesFromImage(string filename)
{
FileStream fs = new FileStream(filename,FileMode.Open,FileAccess.Read);
int length = (int)fs.Length;
byte[] image = new byte[length];
fs.Read(image, 0, length);
fs.Close();
return image;
}
2. 将二进制文件写入数据库
/// <summary>
/// write byte array to database
/// </summary>
public void StoreImageToDB(byte[] image)
{
string connectionString = "Data Source=.;Initial Catalog=MyDB;User Id=sa;Password=123456";
string strSql = "INSERT INTO TestImage(image) Values(@image)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(strSql,connection);
cmd.Parameters.Add("@image", SqlDbType.Image).Value = image;
connection.Open();
cmd.ExecuteNonQuery();
cmd.Clone();
}
}
3. 从数据库中读取图片
/// <summary>
/// get image from database
/// </summary>
public byte[] GetBytesFromDB()
{
string connectionString = "Data Source=.;Initial Catalog=MyDB;User Id=sa;Password=123456";
string strSql = "SELECT top 1 image FROM TestImage";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(strSql,connection);
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
byte[] temp = null;
if (reader.Read())
{
temp = (byte[])reader.GetValue(0);
}
return temp;
}
}
4. 在Controller中添加返回图片的方法
/// <summary>
/// Action that return the image file
/// </summary>
public FileResult Image()
{
//get image from database
byte[] image = GetBytesFromDB();
//return the image to View
return new FileContentResult(image, "image/jpeg");
//or like below
//MemoryStream mem = new MemoryStream(image, 0, image.Length);
//return new FileStreamResult(mem, "image/jpg");
}
5. 在View中显示图片, 将src指定为我们返回图片的Action方法
<img alt="" src="/Home/Image" />
上面的方法都是我们自己实现且用SQL语句存取数据库,其实.NET框架已经给我们封装好了
很多现成的类,再加上 EF 存取数据库可以使我们的代码变得更加 elegant。
1. 前台上传图片
@using (Html.BeginForm("Edit", "Admin", FormMethod.Post,
new { enctype = "multipart/form-data" })) {
<div>Upload new image: <input type="file" name="Image" /></div>
<input type="submit" value="Save" />
}
它相当于 webform 中的 :
<form action="/Admin/Edit" enctype="multipart/form-data" method="post">
enctype = "multipart/form-data" 告诉浏览器将我们的文件流 post 到后台。
2. 将图片存入数据库
[HttpPost]
public ActionResult Edit(Product product, HttpPostedFileBase image) {
if (ModelState.IsValid) {
if (image != null) {
product.ImageMimeType = image.ContentType;
product.ImageData = new byte[image.ContentLength];
image.InputStream.Read(product.ImageData, 0, image.ContentLength);
}
// save the product
repository.SaveProduct(product);
return RedirectToAction("Index");
} else {
// there is something wrong with the data values
return View(product);
}
}
MVC框架会自动封装实例化我们的实体类和文件流并传到 post 方法中。
其中 HttpPostedFileBase 是一个抽象类,实际传过来的对象
是它的子类 HttpPostedFileWrapper 对象。
HttpPostedFileBase 类定义了很多操作文件流的属性和接口。
3. 在 view 中请求显示图片的 action
<img src="@Url.Action("GetImage", "Product", new { Model.ProductID })" />
其中读取图片流的方法如下:
public FileContentResult GetImage(int productId) {
Product prod = repository.Products.FirstOrDefault(p => p.ProductID == productId);
if (prod != null) {
return File(prod.ImageData, prod.ImageMimeType);
} else {
return null;
}
}
其中 FileContentResult 是 ActionResult 的子类 ,action 的返回类型有很多种,它们都继承自抽象类 ActionResult 。
相关文章推荐
- 数据库存取图片并在MVC3中显示在View中
- Silverlight显示数据库二进制字段图片(RadTileView)
- Recyclerview显示数据+GreenDao数据库+跳转传值(图片圆)+MVP
- 【转载】从数据库中读出图片并显示的示例代码
- 图片上传到数据库与显示(转载,C#→VB)
- ASP.NET中存取图片到数据库的示例(转载http://www.knowsky.com/3257.html)
- 数据库存取图片 asp.net 显示到Image控件
- (转载) UITableView 系列一 :基本使用方法 (显示,删除,添加图片,添加样式等
- [ASP] 数据库中 OLEDB 格式 jpeg 图片的读取及显示(原作)
- [ASP] 数据库中 OLEDB 格式 jpeg 图片的读取及显示(原作)
- 从Microsoft SQL Server的PUB数据库读取图片并显示它
- 结合ashx来在DataGrid中显示从数据库中读出的图片
- 如何显示数据库中以 OLE 对象方式存储的 JPEG 图片
- 数据库中存取图片
- 如何读取保存在数据库中的图片显示在DataGrid中
- 如何读取保存在数据库中的图片显示在DataGrid中
- 在DataGrid中显示数据库中的图片
- 将PICTUREBOX中显示的图片,存入数据库中
- web中,如何读取Word内容(包含表格,但不包含图片)并且显示在页面中或保存进数据库中
- 对Oralce数据库存取图片的几种方法