INSERT AND RETRIEVE IMAGE INTO SQL DATABASE USING C#.NET

Posted by Aloktiwari588-19868 under ASP.NET on 1/2/2013 | Points: 10 | Views : 135691 | Status : [Member] | Replies : 17
Sir,
Please Send Me complete Code For the how to insert and retrieve image into sql database using c#.net , i am using visual studio 2010 professional

please send me comlete code for that

Alok Tiwari


Responses

Posted by: Ankitsrist on: 1/2/2013 [Member] Starter | Points: 25

Up
0
Down
i have same question not solved yet trying from long tym....

Aloktiwari588-19868, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Ankitsrist on: 1/2/2013 [Member] Starter | Points: 25

Up
0
Down
insertion of image into database is working fine but dont know how to retrieve it nd display in webpage as same in social networking sites does

Aloktiwari588-19868, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Ankitsrist on: 1/2/2013 [Member] Starter | Points: 25

Up
0
Down
please help us

Aloktiwari588-19868, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Ankitsrist on: 1/2/2013 [Member] Starter | Points: 25

Up
0
Down
bro until others help use my code nd insert image into database

public partial class uploadpic : System.Web.UI.Page

{
dbClass db = new dbClass();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string url, id;
id = (string)Session["id"];
url = "~/ImageViewHandler.ashx?id=" + id;
frame1.Attributes.Add("src", url);

}

}
protected void Button2_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{

if (FileUpload1.PostedFile.ContentType == "image/jpeg")
{
if (FileUpload1.PostedFile.ContentLength < 102400)
{
db.myconnection();
int length = FileUpload1.PostedFile.ContentLength;
byte[] imagebyt = new byte[length];
HttpPostedFile img = FileUpload1.PostedFile;
img.InputStream.Read(imagebyt,0,length );
SqlCommand cmd = new SqlCommand("insert into picsupload(image)values(@image)", db.sqlcon );
cmd.Parameters.Add("@image", SqlDbType.Image).Value=imagebyt;
cmd.ExecuteNonQuery();
Label1.Text = "inserted";
}
else
{
Label1.Text = "select file";
}
}


}
}


make table column id, image...datatype for image should be image

Aloktiwari588-19868, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rabbil on: 1/2/2013 [Member] Starter | Points: 25

Up
0
Down
Hi,

You can achieve this by using a separate handler which would convert the image into byte format and then store it into sql database.
Or you can also follow the below code for saving into DB but be sure you must have defined the image column in your database as VarBinary(max).

if (imagename != "")
{

FileStream fS;

fS= new FileStream(@imagename, FileMode.Open, FileAccess.Read);

//a byte array to read the image

byte[] picbyte = new byte[fs.Length];

fs.Read(picbyte, 0, System.Convert.ToInt32(fs.Length));

fs.Close();

//open the database using odp.net and insert the data

string connstr = @"Data Source=.;Initial Catalog=TestImage;
Persist Security Info=True;User ID=sa";

SqlConnection conn = new SqlConnection(connstr);

conn.Open();

string query;

query = "insert into image_table(id_image,pic) values(" +
textBox1.Text + "," + " @pic)";

SqlParameter picparameter = new SqlParameter();

picparameter.SqlDbType = SqlDbType.Image;

picparameter.ParameterName = "pic";

picparameter.Value = picbyte;

SqlCommand cmd = new SqlCommand(query, conn);

cmd.Parameters.Add(picparameter);

cmd.ExecuteNonQuery();

MessageBox.Show("Image Added");

cmd.Dispose();

conn.Close();

conn.Dispose();

Connection();

}

}


For more clarification refere this

http://www.redmondpie.com/inserting-in-and-retrieving-image-from-sql-server-database-using-c/ http://ifaadasoftware.com/forum/index.php?topic=109.0

"I cannot teach anybody anything. I can only make them think"~ Socrates
Thanks And Regards

Aloktiwari588-19868, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Ankitsrist on: 1/2/2013 [Member] Starter | Points: 25

Up
0
Down
rabbil this is ok but how to retrieve it

Aloktiwari588-19868, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rabbil on: 1/2/2013 [Member] Starter | Points: 25

Up
0
Down
You can check with this link for retrieval
http://www.redmondpie.com/inserting-in-and-retrieving-image-from-sql-server-database-using-c/ and for more code the other link which I've provided above.

Thanks And Regards,
Rabbil

"I cannot teach anybody anything. I can only make them think"~ Socrates
Thanks And Regards

Aloktiwari588-19868, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Ankitsrist on: 1/2/2013 [Member] Starter | Points: 25

Up
0
Down
THANKS RABBIL

Aloktiwari588-19868, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rabbil on: 1/2/2013 [Member] Starter | Points: 25

Up
0
Down
My pleasure.....!!
Happy Coding !!


"I cannot teach anybody anything. I can only make them think"~ Socrates
Thanks And Regards

Aloktiwari588-19868, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Lakhwinder.Ghuman on: 1/3/2013 [Member] Starter | Points: 25

Up
0
Down
You can have following steps to fetch image from the database and display on the page:
Step 1: Create a simple blank web page and write the following code in the Page_Load event:
conn = new SqlConnection(str);

conn.Open();
string id = Convert.ToString(Request.QueryString["Id"]);
strSQL = "";
strSQL = strSQL + " SELECT UserImage from UserPicture ";
strSQL = strSQL + " WHERE UserId = '" + id + "' ";

sql = new SqlCommand(strSQL, conn);
dr = sql.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.Read())
{
Response.ContentType = "image/gif";
Response.BinaryWrite((byte[])dr["snap"]);
}
conn.Close();

This is the general page which can be used for multiple pages to display the image, you just need to pass the Id coresponding to which the image will be retrieved.
Step 2: Create a second page and place a Image control On it, and write the following code in the Page_Load event of second page or in any other event:
Image1.ImageUrl = "FirstPage.aspx?Id=" + "123";


So here 2nd page pass the query string to first page , then first page retrieves the image from database and display it on the Image control on second page.

Best Regards
Lakhwinder Ghuman

Aloktiwari588-19868, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Chikkanti on: 1/4/2013 [Member] Starter | Points: 25
Posted by: Jayakumars on: 3/26/2013 [Member] [MVP] Bronze | Points: 25

Up
0
Down
hi
ankrisit


how to after upload use this code.

Mark as Answer if its helpful to you

Aloktiwari588-19868, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rohanleuva on: 4/16/2013 [Member] Starter | Points: 25

Up
0
Down
Have a look at http://www.aspdotnet-suresh.com/2011/01/how-to-insert-images-into-database-and.html .Hope this helps.

Aloktiwari588-19868, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Shekhar04 on: 6/23/2013 [Member] Starter | Points: 25

Up
0
Down
For retrieve and show images into gridview check the below link
http://chauhanshekhar.blogspot.in/p/how-to-show-images-in-gridview-from.html

For inserting images into database check the below link
http://chauhanshekhar.blogspot.in/p/blog-page_13.html

Aloktiwari588-19868, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Priyagoel_24 on: 7/31/2013 [Member] Starter | Points: 25

Up
0
Down
hello friend,
please tell me . i am design page file upload coding. file save in solution explorer . i make new folder. name is excelfile. there is coding in insert is name,days,hdays,month,years. there is problem.
insert code is going in sql datbase
Regard
Priya

Aloktiwari588-19868, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Priyagoel_24 on: 8/21/2013 [Member] Starter | Points: 25

Up
0
Down
hello friend
try
{
if (cn.State == ConnectionState.Closed)
{
cn.Open();
}
for (int i = 0; i < dt1.Rows.Count - 1; i++)
{
string check = "select name,days,hdays,months,years * from inventory";
ad2.fill = ad2();
string _whr = "select * from inventory where name= 'priya' + dt1.Rows[i][name].ToString()+ = "'," Convert.ToInt32(dt1.Rows[i][days] + hdays = '1'+ Convert.ToInt32(dt1.Rows[i][hdays] + months = '1'+ Convert.ToInt32(dt1.Rows[i][months] + years = '1'+ Convert.ToInt32(dt1.Rows[i][years]+ ")"; how to write where query

if (dt1.Rows.Count > 0)
{ }

else
{

string insert = "insert into inventory(name,days,hdays,months,years)values('" + dt1.Rows[i]["name"].ToString() + "'," + Convert.ToInt32(dt1.Rows[i]["days"]) + "," + Convert.ToInt32(dt1.Rows[i]["hdays"]) + "," + Convert.ToInt32(dt1.Rows[i]["months"]) + "," + Convert.ToInt32(dt1.Rows[i]["years"]) + ")";
SqlCommand ad2 = new SqlCommand(insert, cn);
ad2.ExecuteNonQuery();
}
}
}

Aloktiwari588-19868, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Bandi on: 8/21/2013 [Member] [MVP] Platinum | Points: 25

Up
0
Down
Sample code for upload Images into the folder ....../ImagesExample/FileName.ext
protected void UploadImage()

{
//Get Filename from fileupload control
string filename = Path.GetFileName(fileuploadimages.PostedFile.FileName);
//Save images into Images folder
fileuploadimages.SaveAs(Server.MapPath("ImagesEx/" + filename));
//Getting dbconnection from web.config connectionstring
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnStrings"].ToString());
//Open the database connection
con.Open();
//Query to insert images path and name into database
SqlCommand cmd = new SqlCommand("Insert into ImageUpload(ImageName,Image) values(@ImageName,@ImagePath)", con);
//Passing parameters to query
cmd.Parameters.AddWithValue("@ImageName", filename);
cmd.Parameters.AddWithValue("@ImagePath", "ImagesEx/" + filename);

int count = cmd.ExecuteNonQuery();
//Close dbconnection
con.Close();
}


Mark This Response as Answer
--
Chandu
http://www.dotnetfunda.com/images/dnfmvp.gif

Aloktiwari588-19868, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response