Asp.Net在SqlServer中的圖片存取
來源:互聯網
上載者:User
在使用asp.net將圖片上傳並存入SqlServer中,然後從SqlServer中讀取並顯示出來
一,上傳並存入sqlserver
資料庫結構
create table test
{
id identity(1,1),
FImage image
}
相關的預存程序
Create proc UpdateImage
(
@UpdateImage Image
)
As
Insert Into test(FImage) values(@UpdateImage)
GO
在upphoto.aspx檔案中添加如下:
<input id="UpPhoto" name="UpPhoto" runat="server" type="file">
<asp:Button id="btnAdd" name="btnAdd" runat="server" Text="上傳"></asp:Button>
然後在後置代碼檔案upphoto.aspx.cs添加btnadd按鈕的單擊事件處理代碼:
private void btnAdd_Click(object sender, System.EventArgs e)
{
//獲得圖象並把圖象轉換為byte[]
HttpPostedFile upPhoto=UpPhoto.PostedFile;
int upPhotoLength=upPhoto.ContentLength;
byte[] PhotoArray=new Byte[upPhotoLength];
Stream PhotoStream=upPhoto.InputStream;
PhotoStream.Read(PhotoArray,0,upPhotoLength);
//串連資料庫
SqlConnection conn=new SqlConnection();
conn.ConnectionString="Data Source=localhost;Database=test;User Id=sa;Pwd=sa";
SqlCommand cmd=new SqlCommand("UpdateImage",conn);
cmd.CommandType=CommandType.StoredProcedure;
cmd.Parameters.Add("@UpdateImage",SqlDbType.Image);
cmd.Parameters["@UpdateImage"].Value=PhotoArray;
//如果你希望不使用預存程序來添加圖片把上面四句代碼改為:
//string strSql="Insert into test(FImage) values(@FImage)";
//SqlCommand cmd=new SqlCommand(strSql,conn);
//cmd.Parameters.Add("@FImage",SqlDbType.Image);
//cmd.Parameters["@FImage"].Value=PhotoArray;
conn.open();
cmd.ExecuteNonQuery();
conn.Close();
}
二,從sqlserver中讀取並顯示出來
在需要顯示圖片的地方添加如下代碼:
<asp:image id="imgPhoto" runat="server" ImageUrl="ShowPhoto.aspx"></asp:image>
showphoto.aspx主體代碼:
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
SqlConnection conn=new SqlConnection()
conn.ConnectionString="Data Source=localhost;Database=test;User Id=sa;Pwd=sa";
string strSql="select * from test where id=2";//這裡假設擷取id為2的圖片
SqlCommand cmd=new SqlCommand()
reader.Read();
Response.ContentType="application/octet-stream";
Response.BinaryWrite((Byte[])reader["FImage"]);
Response.End();
reader.Close();
}
}