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-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 !";
}
}