ASP.Netは、画像をデータベースにバイナリで格納し、読み出す
3386 ワード
今日は,画像をデータベースにバイナリ形式で格納し,そこからページに表示する方法を検討した.次はいくつかのキーコードを貼ります.
1.画像をデータベースに保存する
フロントコード:
バックグラウンドコード:
必要な名前空間Data.SqlClient; using System.Drawing; using System.IO;
2.データベースからバイナリ画像を読み出す
実はこれはただ1つの融通のきかない方法を使って、もとはimageの中のsrcをピクチャのサーバーの上の記憶アドレスにして、今srcを1つのページに変えて、このページはデータベースの中のピクチャを表示します.
新しいアイテムを作成した後(一時的にshowImage.aspxと名前を付け)、バックグラウンドに直接コードを追加します.
3.必要な表示画像のページには、上のshowImageを参照する.aspxページgridviewで、ユーザー情報リストを表示するときに、そのユーザーの顔写真を同時に表示します.
1.画像をデータベースに保存する
フロントコード:
<asp:FileUpload ID="FileUploadImage" runat="server" />
バックグラウンドコード:
必要な名前空間Data.SqlClient; using System.Drawing; using System.IO;
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnSubmit_Click(object sender, EventArgs e)
{
byte[] image = new byte[FileUploadImage.PostedFile.ContentLength];
FileUploadImage.PostedFile.InputStream.Read(image, 0, FileUploadImage.PostedFile.ContentLength);
#region //
try
{
string connString = System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString();
SqlConnection conn = new SqlConnection(connString);
SqlCommand command = new SqlCommand("insert into tblUser(Image) values (@image)",conn);
command.Parameters.AddWithValue("@image",image);
conn.Open();
if (command.ExecuteNonQuery() > 0)
{
ScriptManager.RegisterStartupScript(this.Page,this.GetType(),"Success","alert(' !')",true);
}
else
{
ScriptManager.RegisterStartupScript(this.Page,this.GetType(),"Error","alert(' ')",true);
}
conn.Close();
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this.Page,this.GetType(),"Exception","alert('"+ex.Message+"')",true);
}
#endregion
}
2.データベースからバイナリ画像を読み出す
実はこれはただ1つの融通のきかない方法を使って、もとはimageの中のsrcをピクチャのサーバーの上の記憶アドレスにして、今srcを1つのページに変えて、このページはデータベースの中のピクチャを表示します.
新しいアイテムを作成した後(一時的にshowImage.aspxと名前を付け)、バックグラウンドに直接コードを追加します.
protected void Page_Load(object sender, EventArgs e)
{
string connString = System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString();
SqlConnection conn = new SqlConnection(connString);
SqlCommand command = new SqlCommand("select image from tblUser where id=@id", conn);
command.Parameters.AddWithValue("@id",Request.QueryString["id"]);
conn.Open();
byte[] buffer = (byte[])command.ExecuteScalar();
if (buffer == null) return;
Response.ContentType = buffer.ToString(); //System.Byte[]
Response.BinaryWrite(buffer);
}
3.必要な表示画像のページには、上のshowImageを参照する.aspxページgridviewで、ユーザー情報リストを表示するときに、そのユーザーの顔写真を同時に表示します.
<asp:TemplateField HeaderText=" ">
<ItemTemplate>
<image src="showImage.aspx?id=<%#Eval("ID") %>"></image>
</ItemTemplate>
</asp:TemplateField>