MVC中根據后台絕對路徑讀取圖片並顯示在IMG中


數據庫存取圖片並在MVC3中顯示在View中

根據路徑讀取圖片:
byte[] img = System.IO.File.ReadAllBytes(@"d:\xxxx.jpg");

簡介:在有些情況下需要將圖片轉換為二進制流存放在數據庫中,當顯示時再從數據庫中讀出來顯示在界面上。

本文簡單介紹數據庫中圖片的存取方法,並在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 。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM