In this article, I am explaining how to store images and pictures on disk and their path in the database with the help of FileUpload Control and also how to display those images in asp.net GridView Control.
The concept behind this technique is to store the images on disk in a folder that resides in the WebSite root directory while the relative path of the images along with filename is stored in SQL Server database.
First we will start with creating database table that will store the image path. The figure below describes the table structure
As you can see above I have set the ID field to auto increment using the identity property
Next I’ll add a FileUpload and Button to the aspx page.
<div>
<asp:FileUpload ID="FileUpload1" runat="server"/>
<asp:Button ID="btnUpload" runat="server" Text="Upload"
OnClick="btnUpload_Click" />
</div>
Then I am adding a folder called images in my website root directory. Refer figure below.
Connection String
And then I am adding a connection string key to the web.config which will be used to connect to the SQL server Database
<connectionStrings>
<add name="conString"
connectionString="Data Source=.\SQLEXPRESS;database=GridDB;
Integrated Security=true"/>
</connectionStrings >
Upload and Storing the Image Files
The snippet below gets executed when the upload button is clicked. It gets the uploaded image filename and saves the image in images folder. And then inserts the image file path into the database.
C#
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//Save files to disk
FileUpload1.SaveAs(Server.MapPath("images/" + FileName));
//Add Entry to DataBase
String strConnString = System.Configuration.ConfigurationManager
.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
string strQuery = "insert into tblFiles (FileName, FilePath)" +
" values(@FileName, @FilePath)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("@FileName", FileName);
cmd.Parameters.AddWithValue("@FilePath", "images/" + FileName);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
con.Dispose();
}
}
}
VB.Net
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
If FileUpload1.PostedFile IsNot Nothing Then
Dim FileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
'Save files to disk
FileUpload1.SaveAs(Server.MapPath("images/" & FileName))
'Add Entry to DataBase
Dim strConnString As [String] = System.Configuration. _
ConfigurationManager.ConnectionStrings("conString"). _
ConnectionString
Dim con As New SqlConnection(strConnString)
Dim strQuery As String = "insert into tblFiles (FileName, FilePath)" _
& " values(@FileName, @FilePath)"
Dim cmd As New SqlCommand(strQuery)
cmd.Parameters.AddWithValue("@FileName", FileName)
cmd.Parameters.AddWithValue("@FilePath", "images/" & FileName)
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
con.Close()
con.Dispose()
End Try
End If
End Sub
The figure below displays how the data is stored in the database table.
Display Images
Now the next job is to display the images in GridView control. As you can see the below GridView, I have added 2 Bound Fields which displays ID and File Name and a Image Field which displays the image based on the image path that comes from the database.
<div>
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false"
Font-Names = "Arial" >
<Columns>
<asp:BoundField DataField = "ID" HeaderText = "ID" />
<asp:BoundField DataField = "FileName" HeaderText = "Image Name" />
<asp:ImageField DataImageUrlField="FilePath" ControlStyle-Width="100"
ControlStyle-Height = "100" HeaderText = "Preview Image"/>
</Columns>
</asp:GridView>
</div>
The snippet below is used to display the images in the GridView control. As you will notice I am firing a simple select query and the returned datatable is then bind to the GridView Control.
C#
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.
ConnectionStrings["conString"].ConnectionString;
string strQuery = "select * from tblFiles order by ID";
SqlCommand cmd = new SqlCommand(strQuery);
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim dt As New DataTable()
Dim strConnString As [String] = System.Configuration. _
ConfigurationManager.ConnectionStrings("conString")_
.ConnectionString()
Dim strQuery As String = "select * from tblFiles order by ID"
Dim cmd As New SqlCommand(strQuery)
Dim con As New SqlConnection(strConnString)
Dim sda As New SqlDataAdapter()
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
Catch ex As Exception
Response.Write(ex.Message)
Finally
con.Close()
sda.Dispose()
con.Dispose()
End Try
End Sub
The GridView with images is shown in the figure below
You can download the source in VB.net and C# using the link below.
GridViewImagesOnDisk.zip (1.01 mb)
No comments:
Post a Comment