Show Images from Database ASP.Net - asp.net

I am new to ASP.net and have some problem to show images. My designer code is as bellow.
<div id="directory-logo-wrapper" class="floatright">
<table id="wrapper1" runat="server">
<tr>
<td>
<img src="../images/companylogo.png" alt="LogoWrapper" />
<%--<asp:Image ID="Image1" runat="server" Visible="true" alt="LogoWrapper" />--%>
</td>
</tr>
</table>
</div>
My code behind code is as bellow.
protected void ShowImageFile(object sender, EventArgs e)
{
byte[] bytes = {};
bytes = (byte[])GetData("SELECT UploadedLogo FROM Projects WHERE ProjectId =" + id).Rows[0]["UploadedLogo"];
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
//Image1.ImageUrl = "data:image/png;image/jpg;base64," + base64String;
}
private DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = ConnectionInfo.GetConnectionString();
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
Problem: how to set table:wrapper1 img src in code behind because it does not shown in code behind. I tried to do with Image1 but its also not accessing in code behind.
Please help me.
Thanks, Raja

Try Like this
<div id="directory-logo-wrapper" class="floatright">
<table id="wrapper1" runat="server">
<tr>
<td>
<img id="myimage" runat="server" src="../images/companylogo.png" />
</td>
</tr>
</table>
</div>
You can access Src from Code Behind
Try like this
'Get byte array from image file in the database with basic query
SqlDataAdapter myAdapter1 = new SqlDataAdapter("Select [logo] FROM [dbo].[tblCompanyInfo]", GlobalUser.currentConnectionString);
DataTable dt = new DataTable();
myAdapter1.Fill(dt);
foreach (DataRow row in dt.Rows)
{
// Get the byte array from image file
byte[] imgBytes = (byte[])row["logo"];
// If you want convert to a bitmap file
TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
Bitmap MyBitmap = (Bitmap)tc.ConvertFrom(imgBytes );
string imgString = Convert.ToBase64String(imgBytes);
// Set the source with data:image/bmp
myimage.Src = String.Format("data:image/Bmp;base64,{0}\"", imgString);
}
EDIT
Access Image inside GridView
private string m_ConcatUrl;
protected void gridView_RowDataBound(Object sender, GridViewRowEventArgs args)
{
if(args.Row.RowType == DataControlRowType.DataRow)
{
Image imgCtrl = (Image) args.Row.FindControl("imgCtrl");
imgCtrl.ImageUrl = m_ConcatUrl;
}
}
(or)
private string m_ConcatUrl;
protected void gridView_RowDataBound(Object sender, GridViewRowEventArgs args)
{
if(args.Row.RowType == DataControlRowType.DataRow)
{
HtmlImage img = (HtmlImage) args.Row.FindControl("imgCtrl");
imgCtrl.Src= m_ConcatUrl;
}
}

You can try following way:
HTML:
<div id="directory-logo-wrapper" class="floatright">
<table id="wrapper1" runat="server">
<tr>
<td>
<img src='<%# ImageUrl(ProjectId) %>' alt="LogoWrapper" />
<%--<asp:Image ID="Image1" runat="server" Visible="true" alt="LogoWrapper" />--%>
</td>
</tr>
</table>
</div>
Code Behind:
private string ImageUrl(int ProjectId)
{
byte[] bytes = {};
bytes = (byte[])GetData("SELECT UploadedLogo FROM Projects WHERE ProjectId =" + ProjectId).Rows[0]["UploadedLogo"];
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
return "data:image/png;image/jpg;base64," + base64String;
//Image1.ImageUrl = "data:image/png;image/jpg;base64," + base64String;
}
private DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = ConnectionInfo.GetConnectionString();
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
Hope this helps.

Related

Problem with download files from databases through GridView

I have problem with files. I'm trying to download files from databases
through gridview, but after I download them, they are with wrong name and extensions. Their name are my web form name and their extensions are .aspx.
In the database they are saved in the correct format.
Here are my code-behind
public partial class data : System.Web.UI.Page
{
string cs = ConfigurationManager.ConnectionStrings["DecumentsConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillData();
}
}
private void FillData()
{
DataTable dt = new DataTable();
using (SqlConnection cn = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("getDecuments", cn);
cmd.CommandType = CommandType.StoredProcedure;
cn.Open();
SqlDataReader reader = cmd.ExecuteReader();
dt.Load(reader);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
FileInfo filename = new FileInfo(FileUpload1.FileName);
byte[] documentContent = FileUpload1.FileBytes;
string name = filename.Name;
string extnt = filename.Extension;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("savedocument", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#Content", documentContent);
cmd.Parameters.AddWithValue("#extn",extnt);
con.Open();
cmd.ExecuteNonQuery();
}
}
private void Donwload(int id)
{
DataTable dt = new DataTable();
using (SqlConnection cn = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("getdocument", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ID", id);
cn.Open();
SqlDataReader reader = cmd.ExecuteReader();
dt.Load(reader);
}
string name = dt.Rows[0]["name"].ToString();
byte[] document = (byte[])dt.Rows[0]["DocumentContent"];
Response.ClearContent();
Response.ContentType = "application/octetstream";
Response.AddHeader("Content-Dispisition", string.Format("attachment;filename={0}", name));
Response.AddHeader("Content-Lenght", document.Length.ToString());
Response.BinaryWrite(document);
Response.Flush();
Response.Close();
}
protected void OpenDocument(object sender, EventArgs e)
{
LinkButton lnk = (LinkButton)sender;
GridViewRow gr = (GridViewRow)lnk.NamingContainer;
int id = int.Parse(GridView1.DataKeys[gr.RowIndex].Value.ToString());
Donwload(id);
}
}
}
and my html
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text="Document"></asp:Label>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Save" OnClick="Button1_Click" />
<br />
</td>
</tr>
</table>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID">
<Columns>
<asp:TemplateField HeaderText="Documents">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" OnClick="OpenDocument" runat="server" Text='<%# Eval("name") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
</div>
</form>
img

ASP.NET Listview.selectedindex property goes crazy

I'm deleting a single database record from a listview and after deleting I try to navigate in my listview using listView1.selectedindex property, but I have noticed that it highlights the incorrect record (for example I set listView1.selectedindex to 1 but it displays a record which has index 0) . What is wrong? Please help!
protected void deleteButton_Click(object sender, EventArgs e)
{
int id = int.Parse(((Label)ListView1.Items[ListView1.SelectedIndex].FindControl("idLabel")).Text);
using (SqlConnection conn = new SqlConnection(connStr))
{
string Sql = "delete from Employee where id = #id";
conn.Open();
using (SqlCommand dCmd = new SqlCommand(Sql, conn))
{
dCmd.Parameters.AddWithValue("#id", id);
dCmd.ExecuteNonQuery();
}
conn.Close();
}
BindDataFromBaseToListView();
}
BindDataFromBaseToListView method looks so:
private void BindDataFromBaseToListView()
{
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlDataAdapter dAd = new SqlDataAdapter("select * from Employee", conn))
{
DataTable dTable = new DataTable();
dAd.Fill(dTable);
ListView1.DataSourceID = null;
ListView1.DataSource = dTable;
ListView1.DataBind();
}
conn.Close();
}
Instead of using deleteButton_Click event you could use your ListView's OnItemCommand event to get the selected row values and delete the item that you want like the code below:
protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "delete")
{
int id = 0;
if(int.TryParse((e.Item.FindControl("idLabel") as Label).Text, out id))
{
using (SqlConnection conn = new SqlConnection(connStr))
{
string Sql = "delete from Employee where id = #id";
conn.Open();
using (SqlCommand dCmd = new SqlCommand(Sql, conn))
{
dCmd.Parameters.AddWithValue("#id", id);
dCmd.ExecuteNonQuery();
}
conn.Close();
}
BindDataFromBaseToListView();
}
}
}
And on your control's element will look like this:
<asp:ListView ID="ListView1" runat="server" OnItemCommand="ListView1_ItemCommand" .. >
...
<ItemTemplate>
<asp:Button runat="server" CommandName="delete" Text="Delete" ID="DeleteButton" />
...
Let me know if you still have issue with it.

bind image from database to datalist

I am binding image to datalist.
My imagename is in database, i am taking it and wants to bind it to datalist.
I have tried following:
<asp:DataList ID="dlImages" runat="server">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" Height="200px" Width="200px"
ImageUrl='<%# Bind ("PageName","D:\Sagar\Kinston\WebSite\ScreenMasterImages\{0}") %>' runat="server" />
</ItemTemplate>
</asp:DataList>
on pageload i have bounded it as:
ds = gc.GetDataToListBinder("select DISTINCT PageOrderID,PageName from ScreenMaster order by PageOrderID")
dlImages.DataSource = ds.Tables(0)
dlImages.DataBind()
In above code ds is my dataset and gc.GetDataToListBinder(query) returns dataset.
But images are not getting displayed.
What can be the mistake?
EDIT1:
<asp:ImageButton ID="ImageButton1" Height="200px" Width="200px" ImageUrl='<%#Server.HtmlDecode(Eval("PageName","D:\Sagar\Kinston\WebSite\ScreenMasterImages\{0}.jpg")) %>' runat="server" />
Take a minute and read this:
http://www.codeproject.com/Articles/142013/There-is-something-about-Paths-for-Asp-net-beginne
I think this will help you alot.
EDIT:
For the space problem, take a look:
Why does HttpUtility.UrlEncode(HttpUtility.UrlDecode("%20")) return + instead of %20?
Basically:
ImageUrl='<%# Server.HtmlDecode(Bind("MyImage")) %>'
But i recommend that you store your image name without space in db.
EDIT2:
ImageUrl='<%# Eval("MyImage") %>'
ImageUrl='<%# Server.HtmlDecode(Eval("MyImage")) %>'
<asp:DataList ID="DataList1" runat="server" RepeatColumns="3"
RepeatDirection="Horizontal" CellPadding="2"
CellSpacing="2"
UseAccessibleHeader="True" >
<ItemTemplate>
<asp:ImageButton Width="120" Height="120" ID="Image1" ImageUrl='<%# Eval("Imgpath", "") %>' runat="server" />
</asp:Datalist>
.CS
SqlConnection con;
SqlCommand cmd;
string strCon = "Connection String";
SqlDataAdapter da;
protected void AlldataImg()
{
DataTable dt = new DataTable();
string strQuery = "select code,imgpath from SA_Stock order by Code";
cmd = new SqlCommand(strQuery);
con = new SqlConnection(strCon);
da = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
da.SelectCommand = cmd;
da.Fill(dt);
DataList1.DataSource = dt;
DataList1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
da.Dispose();
con.Dispose();
}
}
protected void Page_Load(object sender, EventArgs e)
{
AlldataImg();
}
Put Image Path in database too so that image will appear..
protected void DataListPosts_ItemDataBound(object sender, DataListItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DataRowView dr = (DataRowView)e.Item.DataItem;
Image ImageData = (Image)e.Item.FindControl("ImageData");
if (dr.Row[4].ToString() != "NA")
{
ImageData.Visible = true;
ImageData.ImageUrl = #"ImgPost/" + dr.Row["ImgPath"].ToString();
}
else
ImageData.Visible = false;
}
}
catch (Exception)
{ }
}
its a old topic but i think it can be usefull for anyone
firstly get your data from string
string sqlget = "select Photo from Promoter";
and get it to database dsget
then do that
dsget.Tables[0].Columns.Add("Photopath", typeof(string));
for (int i = 0; i < dsget.Tables[0].Rows.Count; i++)
{
if (dsget.Tables[0].Rows[i]["Photo"].ToString() != null && dsget.Tables[0].Rows[i]["Photo"].ToString() != "")
{
var data = (Byte[])(dsget.Tables[0].Rows[i]["Photo"]);
var stream = new MemoryStream(data);
System.IO.BinaryReader br = new System.IO.BinaryReader(stream);
FileBytes = br.ReadBytes((Int32)stream.Length);
string base64String = Convert.ToBase64String(FileBytes, 0, FileBytes.Length);
dsget.Tables[0].Rows[i]["Photopath"] = "data:image/png;base64," + base64String;
}
}
DataList1.DataSource = dsget.Tables[0];
DataList1.DataBind();
in asp file write the following thing

ASP.NET C# - Dropdown list by using User Control

I am new to ASP.NET
Someone in this forum helped me how to get the dropdown list work wth user countrol and it is working.
In my user control file, VendorListControl.ascx, I have this code below. Please assume that the VendorListControl.ascx.cs works correctly, which is when I select a VendorName, it will fired "ddlVendor_SelectedIndexChanged" to refreshed the "ddlVendorBUList" dropdown list.
<%# Control Language="C#" AutoEventWireup="true" CodeFile="VendorListControl.ascx.cs" Inherits="MyNamespace.VendorListControl" %>
<asp:DropDownList runat="server" ID="ddlVendorList" onselectedindexchanged="ddlVendor_SelectedIndexChanged" AutoPostBack="True" />
<asp:DropDownList runat="server" ID="ddlVendorBUList" AutoPostBack="True" />
<asp:Label runat="server" ID="lblMessage" />
My VendorListControl.ascx.cs code:
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace MyNamespace
{
public partial class VendorListControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillVendors();
}
}
protected void ddlVendor_SelectedIndexChanged(object sender, EventArgs e)
{
int VendorID = Convert.ToInt32(ddlVendorList.SelectedValue.ToString());
FillVendorBU(VendorID);
}
private void FillVendors()
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT VendorID, VendorName FROM MDF_Vendor";
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd; ;
conn.Open();
dAdapter.Fill(objDs);
conn.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
this.ddlVendorList.DataSource = objDs.Tables[0];
this.ddlVendorList.DataTextField = "VendorName";
this.ddlVendorList.DataValueField = "VendorID";
this.ddlVendorList.DataBind();
this.ddlVendorList.Items.Insert(0, "-- Select --");
}
else
{
this.lblMessage.Text = "No Vendor Found";
}
}
private void FillVendorBU(int VendorID)
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT VendorBUID, VendorBUName FROM dbo.MDF_VendorBU WHERE VendorID = #VendorID";
cmd.Parameters.AddWithValue("#VendorID", VendorID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddlVendorBUList.DataSource = objDs.Tables[0];
ddlVendorBUList.DataTextField = "VendorBUName";
ddlVendorBUList.DataValueField = "VendorBUID";
ddlVendorBUList.DataBind();
ddlVendorBUList.Items.Insert(0, "--Select--");
}
else
{
lblMessage.Text = "No states found";
}
}
}
}
Next, in my CreateNewRecord.aspx page, I have this code to include both dropdown list from user control. And I can see the dropdown lists works properly.
<%# Register TagPrefix="uc" TagName="VendorListControl" Src="Controls/VendorListControl.ascx" %>
// Some where in the form
<tr>
<td class="right" width="20%">Vendor Name:</td>
<td>
<uc:VendorListControl runat="server" />
</td>
</tr>
The problem is related to the ID of those two dropdown lists. When I attemp to do the insert record, it seems not to detect the ID for "ddlVendorList" and "ddlVendorBUList" come from user control ascx page. Error " The name 'ddlVendorList' does not exist in the current context"
ExecuteInsert(ddlVendorList.SelectedItem.Text,
ddlVendorBUList.SelectedItem.Text,
MDFAmount.Text,
StartDate.Text,
EndDate.Text,
VendorQuarter.Text,
MDFName.Text,
MDFSummary.Text,
Status.SelectedItem.Text,
CreatedBy.Value
);
Response.Write("<b>Record was successfully added!</b>");
I know I am new to ASP.NET, so please help.
You can put two properties in your VendorListControl to get the ddlVendorList selectedItem text and the ddlVendorBUList selectedItem text.
In VendorListControl.ascx.cs :
public string GetDdlVendorListSelectedItemText
{
get { return this.ddlVendorList.text; }
}
public string GetDdlVendorBUListSelectedItemText
{
get { return this.ddlVendorBUList.text; }
}
Then from your page CreateNewRecord, you can access those properties. You just need to add an id to your control :
<%# Register TagPrefix="uc" TagName="VendorListControl" Src="Controls/VendorListControl.ascx" %>
// Some where in the form
<tr>
<td class="right" width="20%">Vendor Name:</td>
<td>
<uc:VendorListControl id="vendorListControl" runat="server" />
</td>
</tr>
And you can access your properties like this in CreateNewRecord.aspx.cs :
ExecuteInsert(this.vendorListControl.GetDdlVendorListSelectedItemText,
this.vendorListControl.GetDdlVendorBUListSelectedItemText,
MDFAmount.Text,
StartDate.Text,
EndDate.Text,
VendorQuarter.Text,
MDFName.Text,
MDFSummary.Text,
Status.SelectedItem.Text,
CreatedBy.Value
);
You define public property who return SelectedItem.Text in your UserControl.
User Control (Ascx)
public string YourValue
{
get
{
return ddlVendorList.SelectedItem.Text;
}
}
Page (Aspx)
You can use your public property : YourValue.
ExecuteInsert(YourValue,
....... );
Nota : if you wish set value, you define setter on your property
After your update add theses properties
public string YourDdlVendorListSelectedItemText
{
get
{
return this.ddlVendorList.text;
}
}
public string YourDdlVendorBUListSelectedItemText
{
get
{
return this.ddlVendorBUList.text;
}
}

Pls modify this code for retrieving the image from sqldatabase

I am still suffering from retrieving an image from a SQL database. This is my final solution for inserting and retrieving an image from database. Here is all my code:
GUI part:
<div>
<asp:Label ID="lblImage" runat="server" Text="Image"></asp:Label>
<asp:FileUpload ID="imageUpload" runat="server" />
<br />
<asp:Label ID="lblFilename" runat="server" Text="Filename"></asp:Label>
<asp:TextBox ID="txtFilename" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="BtnSave" runat="server" Text="SAVE" onclick="BtnSave_Click" />
<br />
<br />
<br />
<asp:Image ID="Image1" runat="server" />
</div>
And under the Button click event i have written the following code:
protected void BtnSave_Click(object sender, EventArgs e)
{
string uploadFileName = string.Empty;
byte[] imageBytes = null;
if (imageUpload != null && imageUpload.HasFile)
{
uploadFileName = imageUpload.FileName;
imageBytes = imageUpload.FileBytes;
}
string str = ConfigurationManager.ConnectionStrings["ImageConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand("INSERT INTO REPORT_TABLE (IMAGEFIELD,IMAGENAME) VALUES (#image,#filename)", con);
com.Parameters.Add("#image", SqlDbType.Image, imageBytes.Length).Value = imageBytes;
com.Parameters.Add("#filename", SqlDbType.VarChar, 50).Value = uploadFileName;
con.Open();
com.ExecuteNonQuery();
con.Close();
SqlConnection conn = new SqlConnection(str);
string sql = "SELECT * FROM [REPORT_TABLE]";
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds);
DataRow dr = ds.Tables[0].Rows[0];
Byte[] b = (Byte[])dr["IMAGEFIELD"];
MemoryStream ms = new MemoryStream(b);
**this.pictureBox1.Image = Image.FromStream(ms)**; //(This code is for a Windows application but I want to retrieve an image from a web application) so what should be written instead of the highlighted code? In imagecontrol, image id is Image1.
}
you can server image like this:
.....
Image img= Image.FromStream(ms);
Response.Clear();
Response.ContentType = "image/jpeg";
img.Save(Response.OutputStream, ImageFormat.Jpeg);
}
but this will not put image in the <asp:Image ID="Image1" runat="server" /> because it needs image url not the image object :(
what you can do is setup a separate page to serve image and pass it image id or other unique identifier associated with image to show it in the <asp:Image ID="Image1" runat="server" />. simply add new page to your solution say ImageServer.aspx and in page_load write following:
protected void Page_Load(object sender, EventArgs e)
{
if(Request.QueryString.HasValues())
{
var id=Request.QueryString["id"];
if(!string.IsEmptyOrNull(id))
{
SqlConnection conn = new SqlConnection(str);
//CHANGE SELECT TO GET ONLY IMAGE WITH PASSED ID
string sql = "SELECT * FROM [REPORT_TABLE]";
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds);
DataRow dr = ds.Tables[0].Rows[0];
Byte[] b = (Byte[])dr["IMAGEFIELD"];
MemoryStream ms = new MemoryStream(b);
Response.Clear();
Response.ContentType = "image/jpeg";
var img=system.Drawing.Image.FromStream(ms);
img.Save((Response.OutputStream, ImageFormat.Jpeg);
Response.Flush();
return;
}
//HERE YOU MAY RETURN DEFAULT OR ERROR IMAGE
}
}
Now change you button click in upload page as follows:
protected void BtnSave_Click(object sender, EventArgs e)
{
....
//SAVE IMAGE TO DB AND GET IMAGE ID (TO IDENTIFY THIS IMAGE)
image.ImageUrl = "YOUR_SERVER\ImageServer.aspx?id=" + IMAGE_ID;
}

Resources