asp.net(c#)實現(xiàn)從sqlserver存取二進制圖片的代碼
更新時間:2011年09月16日 23:27:07 作者:
有一個員工表Employee,需要保存員工照片(Photo)到數(shù)據(jù)庫(sql server)上。員工照片對應的字段是varbinary(max),也就是要存成二進制文件類型(這和以前討巧地存圖片文件路徑就不相同了),默認可以為空。
下面說說主要實現(xiàn)思路:
1、存取圖片
(1)、將圖片文件轉換為二進制并直接存進sql server
//UploadHelper.cs
/// <summary>
/// 將圖片轉化為長二進制
/// </summary>
/// <param name="photopath"></param>
/// <returns></returns>
public static Byte[] SetImgToByte(string imgPath)
{
FileStream file = new FileStream(imgPath, FileMode.Open, FileAccess.Read);
Byte[] byteData = new Byte[file.Length];
file.Read(byteData, 0, byteData.Length);
file.Close();
return byteData;
}
/// <summary>
/// 將轉換成二進制碼的圖片保存到數(shù)據(jù)庫中
/// </summary>
public static bool SaveEmployeeImg2Db(Employee model, string path)
{
try
{
Byte[] imgBytes = SetImgToByte(path);
model.Photo = imgBytes;
bool flag=EmployeeService.SaveEmployeePhoto(model); //EmployeeService是公司內部的庫調用,插入或者更新照片,這里不透露細節(jié)
return flag;
}
catch (Exception ex)
{
throw ex;
}
}
(2)、在網頁中上傳圖片
/// <summary>
/// 上傳圖片
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnUpload_Click(object sender, EventArgs e)
{
string serverPath = Server.MapPath("~/images/");
if (this.fuPhoto.HasFile) //fuPhoto是fileupload控件
{
string fileName = this.fuPhoto.PostedFile.FileName;
FileInfo fi = new FileInfo(fileName);
string mimeType = this.fuPhoto.PostedFile.ContentType.ToLower();
if (mimeType.IndexOf("image") < 0)
{
//("上傳的照片格式不對");
}
else if(fi.Length > 2* 1024 * 1024)
{
//圖片大于2M,重新處理
}
else
{
string saveFilePath = serverPath + DateTime.Now.ToString("yyyyMMddHHmmss") + fileName;
try
{
//先存圖片到服務器
this.fuPhoto.PostedFile.SaveAs(saveFilePath);
//轉成二進制
Employee model = new Employee(int.Parse(id)); //id是EmployeeId,這里是模擬字段
bool flag = UploadHelper.SaveEmployeeImg2Db(model, saveFilePath);
}
catch
{
//("照片上傳失敗");
}
finally
{
//最后刪掉該圖片
if (System.IO.File.Exists(saveFilePath))
{
System.IO.File.Delete(saveFilePath);
}
}
}
}
else
{
//("全選擇要上傳的照片");
}
}
(3)、從數(shù)據(jù)庫取出照片(返回格式Image)
//UploadHelper.cs
/// <summary>
/// 將二進制轉化為圖片Image
/// </summary>
/// <param name="photopath"></param>
/// <returns></returns>
public static System.Drawing.Image GetImgFromByte(Employee model)
{
System.Drawing.Image img = null;
try
{
Stream stream = new MemoryStream(model.Photo);
img = System.Drawing.Image.FromStream(stream,false);
}
catch
{
img = null;
}
return img;
}
上面的這個方法取出來之后,如果在winform下,直接給一個PictureBox的Image屬性賦值就可以了??墒莣eb下沒有這么強大的控件,所以,就有了下面的步驟。
2、直接在網頁中以流的形式顯示圖片
(1)、生成圖片流頁面(ImgHelper .aspx)
這個頁面的設計頁面什么也沒有,類文件如下:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// 圖片輔助類
/// </summary>
public partial class ImgHelper : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Request["employeeId"])) //需要顯示照片的頁面?zhèn)鬟f的員工id
{
int employeeId = int.Parse(Request["employeeId"]);
Employee model = //EmployeeService.GetEmployeeByCondition(new Employee(employeeId))[0] as Employee; //內部函數(shù) 查找一個員工 不透漏細節(jié)
try
{
Byte[] byteImg = model.Photo;
Stream stream = new MemoryStream(byteImg);
System.Drawing.Bitmap img =(System.Drawing.Bitmap) System.Drawing.Bitmap.FromStream(stream, false); //轉換成Bitmap
Response.Buffer = false;
Response.ContentType = "image/jpg";
Response.AddHeader("Content-Disposition", "attachment;filename=photo.jpg");//照片名稱叫photo.jpg
Response.BinaryWrite(byteImg);//寫入二進制流
Response.End();
}
catch
{
Response.End();
}
}
}
}
(2)、顯示照片的頁面調用ImgHelper .aspx
在頁面加載的時候,給圖片控件賦值如下:
this.imgPhoto.ImageUrl = "/ImgHelper.aspx?employeeId="+tmpEmployee.Id.ToString(); //imgPhoto是圖片控件
總體來說,一存一取,對于winform是很方便的,但是對于webform,我們需要稍微有一個轉化的思路。如果有牛人寫出像winform下那種直接綁定Image對象的控件更好了。上面代碼測試通過,希望對你有幫助。
1、存取圖片
(1)、將圖片文件轉換為二進制并直接存進sql server
復制代碼 代碼如下:
//UploadHelper.cs
/// <summary>
/// 將圖片轉化為長二進制
/// </summary>
/// <param name="photopath"></param>
/// <returns></returns>
public static Byte[] SetImgToByte(string imgPath)
{
FileStream file = new FileStream(imgPath, FileMode.Open, FileAccess.Read);
Byte[] byteData = new Byte[file.Length];
file.Read(byteData, 0, byteData.Length);
file.Close();
return byteData;
}
/// <summary>
/// 將轉換成二進制碼的圖片保存到數(shù)據(jù)庫中
/// </summary>
public static bool SaveEmployeeImg2Db(Employee model, string path)
{
try
{
Byte[] imgBytes = SetImgToByte(path);
model.Photo = imgBytes;
bool flag=EmployeeService.SaveEmployeePhoto(model); //EmployeeService是公司內部的庫調用,插入或者更新照片,這里不透露細節(jié)
return flag;
}
catch (Exception ex)
{
throw ex;
}
}
(2)、在網頁中上傳圖片
復制代碼 代碼如下:
/// <summary>
/// 上傳圖片
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnUpload_Click(object sender, EventArgs e)
{
string serverPath = Server.MapPath("~/images/");
if (this.fuPhoto.HasFile) //fuPhoto是fileupload控件
{
string fileName = this.fuPhoto.PostedFile.FileName;
FileInfo fi = new FileInfo(fileName);
string mimeType = this.fuPhoto.PostedFile.ContentType.ToLower();
if (mimeType.IndexOf("image") < 0)
{
//("上傳的照片格式不對");
}
else if(fi.Length > 2* 1024 * 1024)
{
//圖片大于2M,重新處理
}
else
{
string saveFilePath = serverPath + DateTime.Now.ToString("yyyyMMddHHmmss") + fileName;
try
{
//先存圖片到服務器
this.fuPhoto.PostedFile.SaveAs(saveFilePath);
//轉成二進制
Employee model = new Employee(int.Parse(id)); //id是EmployeeId,這里是模擬字段
bool flag = UploadHelper.SaveEmployeeImg2Db(model, saveFilePath);
}
catch
{
//("照片上傳失敗");
}
finally
{
//最后刪掉該圖片
if (System.IO.File.Exists(saveFilePath))
{
System.IO.File.Delete(saveFilePath);
}
}
}
}
else
{
//("全選擇要上傳的照片");
}
}
(3)、從數(shù)據(jù)庫取出照片(返回格式Image)
復制代碼 代碼如下:
//UploadHelper.cs
/// <summary>
/// 將二進制轉化為圖片Image
/// </summary>
/// <param name="photopath"></param>
/// <returns></returns>
public static System.Drawing.Image GetImgFromByte(Employee model)
{
System.Drawing.Image img = null;
try
{
Stream stream = new MemoryStream(model.Photo);
img = System.Drawing.Image.FromStream(stream,false);
}
catch
{
img = null;
}
return img;
}
上面的這個方法取出來之后,如果在winform下,直接給一個PictureBox的Image屬性賦值就可以了??墒莣eb下沒有這么強大的控件,所以,就有了下面的步驟。
2、直接在網頁中以流的形式顯示圖片
(1)、生成圖片流頁面(ImgHelper .aspx)
這個頁面的設計頁面什么也沒有,類文件如下:
復制代碼 代碼如下:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// 圖片輔助類
/// </summary>
public partial class ImgHelper : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Request["employeeId"])) //需要顯示照片的頁面?zhèn)鬟f的員工id
{
int employeeId = int.Parse(Request["employeeId"]);
Employee model = //EmployeeService.GetEmployeeByCondition(new Employee(employeeId))[0] as Employee; //內部函數(shù) 查找一個員工 不透漏細節(jié)
try
{
Byte[] byteImg = model.Photo;
Stream stream = new MemoryStream(byteImg);
System.Drawing.Bitmap img =(System.Drawing.Bitmap) System.Drawing.Bitmap.FromStream(stream, false); //轉換成Bitmap
Response.Buffer = false;
Response.ContentType = "image/jpg";
Response.AddHeader("Content-Disposition", "attachment;filename=photo.jpg");//照片名稱叫photo.jpg
Response.BinaryWrite(byteImg);//寫入二進制流
Response.End();
}
catch
{
Response.End();
}
}
}
}
(2)、顯示照片的頁面調用ImgHelper .aspx
在頁面加載的時候,給圖片控件賦值如下:
復制代碼 代碼如下:
this.imgPhoto.ImageUrl = "/ImgHelper.aspx?employeeId="+tmpEmployee.Id.ToString(); //imgPhoto是圖片控件
總體來說,一存一取,對于winform是很方便的,但是對于webform,我們需要稍微有一個轉化的思路。如果有牛人寫出像winform下那種直接綁定Image對象的控件更好了。上面代碼測試通過,希望對你有幫助。
您可能感興趣的文章:
- SQL Server中調用C#類中的方法實例(使用.NET程序集)
- C#實現(xiàn)連接SQL Server2012數(shù)據(jù)庫并執(zhí)行SQL語句的方法
- C#連接到sql server2008數(shù)據(jù)庫的實例代碼
- C#實現(xiàn)的sqlserver操作類實例
- C#訪問SQLServer增刪改查代碼實例
- C#獲取所有SQL Server數(shù)據(jù)庫名稱的方法
- C#如何實現(xiàn)對sql server數(shù)據(jù)庫的增刪改查
- C#獲取存儲過程返回值和輸出參數(shù)值的方法
- C# 調用存儲過程簡單完整的實例代碼
- C#中如何執(zhí)行存儲過程方法
- C# Ado.net實現(xiàn)讀取SQLServer數(shù)據(jù)庫存儲過程列表及參數(shù)信息示例
相關文章
.Net Web Api中利用FluentValidate進行參數(shù)驗證的方法
最近在做Web API,用到了流式驗證,就簡單的說說這個流式驗證,下面這篇文章主要給大家介紹了關于.Net Web Api中利用FluentValidate進行參數(shù)驗證的相關資料,,需要的朋友可以參考借鑒,下面隨著小編來一起學習學習吧2018-07-07IIS 瀏覽aspx頁面出現(xiàn)無法顯示XML頁的解決方法分享
這篇文章介紹了IIS 瀏覽aspx頁面出現(xiàn)無法顯示XML頁的解決方法,有需要的朋友可以參考一下2013-11-11.NET Core跨平臺串口通訊使用SerialPortStream基礎類庫問題解決
這篇文章介紹了.NET Core跨平臺串口通訊使用SerialPortStream基礎類庫問題解決,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-01-01.net面向對象之多線程(Multithreading)及 多線程高級應用
這篇文章主要介紹.net面向對象程序設計階段多線程Multithreading及多線程高級應用的介紹,需要的朋友可以參考下2015-07-07