How to store ImageURL into database and deleting Image from Image folder?


Hi friends

There are  two method to store image in database.

1. Stroring Image in database as binary formate

2.Storing ImageURL in database and Image in Local “Images” Folder

If we will follow method 1, then it will increase the server overloading. If we have fetch more images from database it will take more time to display and sometime it will also give error and displaying Image will be very slow.

If we will follow method 2,Then Image URL will store in database and Image will store in”Images” folder. So while fetching Image from database, we have to fetch only ImageURL , so performance of displaying Image will be very fast as compare to method 1.

But I have seen many person, they will follow method 2. But while deleting Image, they will only delete ImageURL from database. they don’t delete Image from Image-folder.So every time, Image folder size will be keep on increasing.

I have prepared some code for Inserting ImageURL into database , Image into ImageFolder and while deleting Image,It will delete from ImageFolder.

Step1: Create the Default Page with EmpName and Image Field

Step2: take a gridview control from Toolbar for displaying the Image

Asp.net HTML code will be like this

<%@ Page Language=”C#” AutoEventWireup=”true”  CodeFile=”Default.aspx.cs” Inherits=”_Default” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head runat=”server”>
<title></title>
<style type=”text/css”>
.style1
{
width: 100%;
}
.gg
{
margin-left:100px;
}
.style2
{
width: 115px;
}
</style>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>

<table class=”gg”>
<tr>
<td class=”style2″>
EmpName</td>
<td>
<asp:TextBox ID=”TextBox1″ runat=”server” Width=”166px”></asp:TextBox>
</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td class=”style2″>
Image</td>
<td>
<asp:FileUpload ID=”FileUpload1″ runat=”server” />
</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td class=”style2″>
&nbsp;</td>
<td>
<asp:Button ID=”BtnSubmit” runat=”server” Text=”Submit”
onclick=”BtnSubmit_Click” />
</td>
<td>
&nbsp;</td>
</tr>
</table>

</div>
<br />
<br />

<div class=”gg”>

<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False”
CellPadding=”4″ ForeColor=”#333333″ GridLines=”None”
onpageindexchanging=”GridView1_PageIndexChanging”
onrowcommand=”GridView1_RowCommand” onrowdeleting=”GridView1_RowDeleting”
onrowediting=”GridView1_RowEditing”>
<RowStyle BackColor=”#EFF3FB” />
<Columns>
<asp:TemplateField HeaderText=”SI.No”>
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText=”EmpName” DataField=”EmpName” />
<asp:TemplateField HeaderText=”Image”>
<ItemTemplate>
<asp:Image ID=”Img1″ runat=”server” ImageUrl='<%#Eval(“Image1″)%>’  Height=”100px” Width=”100px” />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Action”>
<ItemTemplate>
<asp:LinkButton runat=”server” ID=”lnk_Delete” Text=”Delete” CausesValidation=”false” CommandName=”Delete” CommandArgument='<%# Eval(“Id”) %>’ OnClientClick=”return confirm(‘Are you sure?’)”/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor=”#507CD1″ Font-Bold=”True” ForeColor=”White” />
<PagerStyle BackColor=”#2461BF” ForeColor=”White” HorizontalAlign=”Center” />
<SelectedRowStyle BackColor=”#D1DDF1″ Font-Bold=”True” ForeColor=”#333333″ />
<HeaderStyle BackColor=”#507CD1″ Font-Bold=”True” ForeColor=”White” />
<EditRowStyle BackColor=”#2461BF” />
<AlternatingRowStyle BackColor=”White” />
</asp:GridView>

</div>
</form>
</body>
</html>

Step 3: Create a Database for EmpName,ImageURL Like this:

Step4: Keep the Image folder Name Like this Image

Step 5:

Write the code behind C# Code like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
SqlConnection con=new SqlConnection(“Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True”);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillgrid();
}

}

protected void fillgrid()
{
SqlCommand cmd = new SqlCommand(“Select *from tblEmp”, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
else
{
GridView1.DataSource = null;
GridView1.DataBind();
}
}

protected void BtnSubmit_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileExt = Path.GetExtension(FileUpload1.FileName).ToLower();
//Code for Unique FileName
fetchmaxId();
string bb = ViewState[“MaxId”].ToString();

string fileName = bb+Path.GetFileName(FileUpload1.FileName);

string dbfilePath = @”~/Images/” +fileName;
if (fileName != string.Empty)
{
try
{
if (fileExt == “.gif” || fileExt == “.jpg” || fileExt == “.jpeg” || fileExt == “png” || fileExt == “.swf” || fileExt == “.bmp”)
{
FileUpload1.SaveAs(Server.MapPath(@”~/images/”) + fileName);
}
else
{
Response.Write(“You can upload only jpg ,jpg,gif,swf,bmp files…”);
}
}
catch (Exception ex)
{
throw ex;
}
}

//code for Insert into database and Image In Images Folder

SqlCommand cmd = new SqlCommand(“Insert into tblEmp(EmpName,Image1) values(@EmpName,@Image1)”, con);
cmd.Parameters.AddWithValue(“@EmpName”, TextBox1.Text);
cmd.Parameters.AddWithValue(“@Image1”, dbfilePath);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
TextBox1.Text = “”;
fillgrid();
}

}

protected void fetchmaxId()
{
SqlCommand cmd = new SqlCommand(“Select Max(Id)+1 as Id from tblEmp”, con);
SqlDataAdapter da=new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
ViewState[“MaxId”] = dt.Rows[0][“Id”].ToString();

}

}

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{

}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{

}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{

}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == “Delete”)
{
int id1 = Convert.ToInt32(e.CommandArgument);
ViewState[“Id”] = id1;

//code for Fetching ImageURL
fetchURL();

//Code for Deleting in database
SqlCommand cmd = new SqlCommand(“Delete from tblEmp where Id=@Id”, con);
cmd.Parameters.AddWithValue(“@Id”, id1);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
fillgrid();

//code for Deleting Image in folder
string fPath = ViewState[“ImgUrl”].ToString();
string fPath1 = Server.MapPath(fPath);

System.IO.File.Delete(fPath1);
}

}

protected void fetchURL()
{
SqlCommand cmd = new SqlCommand(“Select Image1 from tblEmp where Id=@Id”, con);
cmd.Parameters.AddWithValue(“@Id”, ViewState[“Id”]);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
ViewState[“ImgUrl”] = dt.Rows[0][“Image1”].ToString();
//string fPath = Server.MapPath(ViewState[“ImgUrl”]);
}
}
}

Step 6: Compile the code:

Save some Name and Image

Step 7: Check the database table

Step 8: Check the Image Folder. You will get all image into Image folder and Image URL into datebase

you will see like this

Now delete the Image, Then it will be delete from database and Image folder.

If you have any question, fell free to post comment.

<table class=”gg”>
<tr>
<td class=”style2″>
EmpName</td>
<td>
<asp:TextBox ID=”TextBox1″ runat=”server” Width=”166px”></asp:TextBox>
</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td class=”style2″>
Image</td>
<td>
<asp:FileUpload ID=”FileUpload1″ runat=”server” />
</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td class=”style2″>
&nbsp;</td>
<td>
<asp:Button ID=”BtnSubmit” runat=”server” Text=”Submit”
onclick=”BtnSubmit_Click” />
</td>
<td>
&nbsp;</td>
</tr>
</table>
Advertisement

5 thoughts on “How to store ImageURL into database and deleting Image from Image folder?

  1. Nuno Miguel November 3, 2012 / 3:28 pm

    Hi! This script is very good! I try to implement it but it doesn’t work. Do you have it online to download? Thank you. Miguel

  2. KrishnaChaitanya November 26, 2013 / 6:04 am

    Hi Iam using ur Code for Uploading Images and Deleting Images. But while deleting a Image from Gridview It raising the error at
    Gridview_RowCommand at
    int id1 = Convert.ToInt32(e.CommandArgument);
    i.e,
    System.FormatException: Input string was not in a correct format.
    Is there any Solution for this

  3. Chandra Dev November 30, 2013 / 2:38 am

    Hi,

    Have u downloaded from above URL ? That is the type cast issue. You check there what value is coming for e.CommandArgument using debugger.

  4. you could look here June 15, 2014 / 4:57 am

    With havin so much content and articles do you ever run into any
    problems of plagorism or copyright infringement? My website has a lot
    of unique content I’ve either written myself or outsourced
    but it seems a lot of it is popping it up all over the internet without my permission.
    Do you know any solutions to help stop content from being ripped off?
    I’d certainly appreciate it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.