且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将图像保存在数据库中并在asp.net上显示图像

更新时间:2021-08-13 22:18:49

Select file to save into the database: 

<asp:fileupload runat="server" id="FileUpload1" xmlns:asp="#unknown" />

<asp:button runat="server" id="btnSave" onclick="SaveToTheDatabase" text="Save to the database" xmlns:asp="#unknown" />

<p><asp:label id="lblMessage" runat="server" enableviewstate="false" xmlns:asp="#unknown" /></p>





http://www.dotnetfunda.com/articles/show/1084/saving-images-into-数据库在aspnet中并显示到网格 [ ^ ]





http://www.dotnetfunda.com/articles/show/1084/saving-images-into-the-database-in-aspnet-and-displaying-to-the-gridvi[^]

protected void SaveToTheDatabase(object sender, EventArgs e)

{

string fileName = FileUpload1.PostedFile.FileName;

int fileLength = FileUpload1.PostedFile.ContentLength;

 

byte[] imageBytes = new byte[fileLength];

FileUpload1.PostedFile.InputStream.Read(imageBytes, 0, fileLength);

 

string connStr = ConfigurationManager.AppSettings["ConnStr"].ToString();

using (SqlConnection conn = new SqlConnection(connStr))

{

string sql = "INSERT INTO ImageUpload (PictureName, PictureFile) VALUES (@pictureName, @pictureFile)";

SqlParameter[] prms = new SqlParameter[2];

prms[0] = new SqlParameter("@pictureName", SqlDbType.VarChar, 50);

prms[0].Value = fileName;

prms[1] = new SqlParameter("@pictureFile", SqlDbType.Image);

prms[1].Value = imageBytes;

using (SqlCommand cmd = new SqlCommand(sql, conn))

{

cmd.Parameters.AddRange(prms);

conn.Open();

cmd.ExecuteNonQuery();

conn.Close();

}

lblMessage.Text = "Picture uploaded successsfully !";

}

}