In this article, we learn how to save and insert images into database. So, first create database called Image as shown in below.
Now, Create a UI page called ImageUploadDemo.aspx and add below code.
Now, add below code to the ImageUploadDemo.aspx.cs Page. In below code we write some logic to insert image into database and save image into folder called images.
web.config
Demo
Now, Create a UI page called ImageUploadDemo.aspx and add below code.
<table>
<tr>
<td>
<asp:Label ID="lbl_fileupload" runat="server" Text="Upload File"></asp:Label>
</td>
<td>
<asp:FileUpload ID="FileUpload1" runat="server" />
</td>
</tr>
<tr>
<td>
<asp:Button ID="btn_save" runat="server" Text="Upload" OnClick="btn_save_Click" />
</td>
<td>
</td>
</tr>
</table>
Now, add below code to the ImageUploadDemo.aspx.cs Page. In below code we write some logic to insert image into database and save image into folder called images.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Image"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_save_Click(object sender, EventArgs e)
{
string fileName = FileUpload1.FileName;
string fileExt = Path.GetExtension(fileName).ToLower();
if (fileExt == ".jpg" || fileExt == ".gif" || fileExt == ".jpeg" || fileExt == ".png")
{
FileUpload1.SaveAs(Server.MapPath("~/images/") + FileUpload1.FileName);
string imageUrl = "~/Images/" + fileName;
SqlCommand com = new SqlCommand();
com.CommandText = "insert into Image(image_name,image_url) values(@image_name, @image_url)";
com.Connection = con;
com.Parameters.AddWithValue("@image_name", fileName);
com.Parameters.AddWithValue("@image_url", imageUrl);
con.Open();
com.ExecuteNonQuery();
con.Close();
}
}
web.config
<configuration>
<connectionStrings>
<add name="Image" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=E:\Demo\FileUploadDemo\App_Data\Database.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
</system.web>
</configuration>
Demo
0 comments:
Post a Comment