MVC中根据后台绝对路径读取图片并显示在IMG中

数据库存取图片并在MVC3中显示在View中

根据路径读取图片:
1
byte [] img = System.IO.File.ReadAllBytes( @"d:\xxxx.jpg" );

简介:在有些情况下需要将图片转换为二进制流存放在数据库中,当显示时再从数据库中读出来显示在界面上。

本文简单介绍数据库中图片的存取方法,并在MVC3中显示在Razor视图中。仅供初学者参考学习。

1. 将图片转换为二进制流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/// <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. 将二进制文件写入数据库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/// <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 。

转载于:https://www.cnblogs.com/wanzhongjun/p/6852388.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值