Hello Friends,
In this article i am going to tell you how to upload image from Database and retrieve in image control using asp.net and c#.net code. Because most of people get so many error while uploading image from database.
Here are Step by Step Code to upload image from datbase.
Step-1 –
First of all create default.aspx page and mention TextBox (txtid),
FileUpload(picture) , 2 Button(btnShow, btnSave)
1 Image control(Image1).
{ <asp:Image ID="Image1"
runat="server"
ImageUrl='<%#"ShowImage.ashx?id="
+ Eval("imgid")%>' Height="100px"Width="100px" /> }
Step-2 –
Create Database Table
Database Name-*****
Table Name-imgtable
Field Name- imgid(numeric), img(image)
Step-3 –
Code on btnSave_Click
FileUpload img = (FileUpload)picture;
Byte[]
byt = null;
if
(img.HasFile && img.PostedFile != null)
{
HttpPostedFile
File =picture.PostedFile;
byt = new
Byte[File.ContentLength];
File.InputStream.Read(byt, 0,
File.ContentLength);
SqlConnection
cnn = new SqlConnection();
cnn.ConnectionString = "server=admin-pc; database=college; uid=sa;
pwd=sa";
cnn.Open();
SqlCommand
cmd = new SqlCommand("insert into imgtable(imgid,img) values(@id,@img)",cnn);
cmd.Parameters.AddWithValue("@id", txtid.Text);
cmd.Parameters.AddWithValue("@img", byt);
cmd.ExecuteNonQuery();
// if you
want to see image instantly after save use the below single line code
Image1.ImageUrl = "~/ShowImage.ashx?id=" + txtid.Text;
cnn.Close();
}
Step-4 –
Code on btnShow_Click
Image1.ImageUrl = "~/ShowImage.ashx?id="
+ txtid.Text;
Step-5 –
Create Generic Handlar class
Name is ShowImage.ashx
Write code
<%@ WebHandler Language="C#"
Class="WebApplicationTest.ShowImage"
%>
using System;
using
System.Web;
using
System.Data.SqlClient;
using
System.Data;
using System.IO;
namespace WebApplicationTest
public class ShowImage : IHttpHandler {
public void ProcessRequest (HttpContext
context)
{
string
id;
if
(context.Request.QueryString["id"]
!= null)
id=context.Request.QueryString["id"];
else
throw
new ArgumentException("No parameter specified");
context.Response.ContentType = "image/jpeg";
context.Response.ContentType = "image/bmp";
Stream
strm = ShowEmpImage(id);
byte[]
buffer = new byte[4096];
int
byteSeq = strm.Read(buffer, 0, 4096);
while
(byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0,
4096);
}
//context.Response.BinaryWrite(buffer);
}
public Stream ShowEmpImage(string
id)
{
SqlConnection
con = new SqlConnection("server=admin-pc; database=college; uid=sa;
pwd=sa");
con.Open();
SqlCommand
cmd = new SqlCommand("SELECT img FROM imgtable WHERE imgid ='"
+ id + "'",con);
object
img = cmd.ExecuteScalar();
try
{
return
new MemoryStream((byte[])img);
}
catch
{
return
null;
}
finally
{
con.Close();
}
}
public bool IsReusable {
get {
return
false;
}}}
No comments:
Post a Comment