In this article I will explain with an example, how to retrieve Images using File Path stored in Database in ASP.Net using C# and VB.Net.
Image files will be uploaded and then will be saved into a Folder (Directory) on disk. The Path of the saved files will be inserted into SQL Server Database Table.
Finally using the Path, the Image Files will be retrieved and displayed in GridView along with feature to Zoom the Image using jQuery.
Database
This article makes use of a table named Files whose schema is defined as follows.
Note: You can download the database table SQL by clicking the download link below.
HTML Markup
The following HTML Markup consists of an ASP.Net FileUpload control, Button, a GridView and an HTML DIV.
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick = "Upload" />
<hr />
<asp:GridView ID="gvImages" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="FileId" HeaderText="Image Id" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:ImageField DataImageUrlField="Path" HeaderText="Image" />
</Columns>
</asp:GridView>
<div id="dialog" style="display: none">
</div>
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.IO
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Displaying Images using Path stored in database in ASP.Net GridView
Inside the Page Load event handler, the records from the database table are fetched and are used to populate the GridView control.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Files", conn))
{
DataTable dt = new DataTable();
sda.Fill(dt);
gvImages.DataSource = dt;
gvImages.DataBind();
}
}
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using conn As SqlConnection = New SqlConnection(constr)
Using sda As SqlDataAdapter = New SqlDataAdapter("SELECT * FROM Files", conn)
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
gvImages.DataSource = dt
gvImages.DataBind()
End Using
End Using
End If
End Sub
Uploading Image and saving Image Path in SQL Server database in ASP.Net
The following event handler gets called when an Image file is selected and the Upload Button is clicked.
The uploaded Image file is first saved into a Folder named Uploads within the Project Folder and then the Name and the Path of the Image file is inserted into the SQL Server database table.
Note: The Relative Path of the Image file will be saved in the database for ease of conversion to Absolute Path or Absolute URL.
C#
protected void Upload(object sender, EventArgs e)
{
//Extract Image File Name.
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//Set the Image File Path.
string filePath = "~/Uploads/" + fileName;
//Save the Image File in Folder.
FileUpload1.PostedFile.SaveAs(Server.MapPath(filePath));
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
string sql = "INSERT INTO Files VALUES(@Name, @Path)";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@Name", fileName);
cmd.Parameters.AddWithValue("@Path", filePath);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
VB.Net
Protected Sub Upload(ByVal sender As Object, ByVal e As EventArgs)
'Extract Image File Name.
Dim fileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
'Set the Image File Path.
Dim filePath As String = "~/Uploads/" & fileName
'Save the Image File in Folder.
FileUpload1.PostedFile.SaveAs(Server.MapPath(filePath))
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using conn As SqlConnection = New SqlConnection(constr)
Dim sql As String = "INSERT INTO Files VALUES(@Name, @Path)"
Using cmd As SqlCommand = New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("@Name", fileName)
cmd.Parameters.AddWithValue("@Path", filePath)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Using
End Using
Response.Redirect(Request.Url.AbsoluteUri)
End Sub
Implement Zoom feature when Image is clicked using jQuery
A jQuery click event handler is assigned to all the HTML Image elements within the GridView. When an HTML Image element is clicked, the Image element is cloned and displayed in larger size within a jQuery UI Model Popup.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/themes/start/jquery-ui.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function () {
$("#dialog").dialog({
autoOpen: false,
modal: true,
height: 600,
width: 600,
title: "Zoomed Image"
});
$("[id*=gvImages] img").click(function () {
$('#dialog').html('');
$('#dialog').append($(this).clone());
$('#dialog').dialog('open');
});
});
</script>
Screenshots
Uploading and displaying the Image Files
Inserted records of Image files
Downloads