.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> ASP.NET >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Read / Write Image into SQL Server in ASP.NET Part - 1

Posted By:Pankaj Mishra       Posted Date: September 01, 2008    Points: 25    Category: ASP.NET    URL: http://www.dotnetspark.com  
 

Hi,

  This article shows how to save image into Database SQL Server. First Create a webpage and just drag and drop FileUpload Control from toolbox 

:FileUpload ID="File1" runat="server" />

  Then in Button Click event Write below lines of code

  int contentLength = File1.PostedFile.ContentLength;
    byte[] bytePic = new byte[contentLength];
    File1.PostedFile.InputStream.Read (bytePic, 0, contentLength); // File1 Is fileUpload control

   SqlConnection myConn = new SqlConnection (@"server=Myserver;database=MyDB;uid=sa;pwd=sa");
    try
    {
        connection.Open ();
        SqlCommand cmd = new SqlCommand ("insert into ImageTable (pic) values (@pic)", myConn);
        cmd.Parameters.Add ("@pic", BytePic);
        cmd.ExecuteNonQuery ();
    }
    catch(Exception ex)
   {
       throw ex;
   }
    finally
    {
        connection.Close ();
    }

Namespace used in above code are.

Using System;
Using System.Data;
Using System.Data.SqlClient;

  And you are done your image is saved to Database in Table ImageTable

Cheers
Pankaj

 Subscribe to Articles

     

Further Readings:

Responses
Author: Syed         Company URL: http://www.dotnetspark.com
Posted Date: September 05, 2008

int contentLength = File1.PostedFile.ContentLength;

in the above line what is File1? is that a new instance of FileUpload class..?
Author: Pankaj Mishra         Company URL: http://www.dotnetspark.com
Posted Date: September 05, 2008

Hi Syed,

File1 is FileUpload webserver Control that is been used in above code. I have commented the above lines of code suggested by you.

Thanks
Pankaj
Author: Syed         Company URL: http://www.dotnetspark.com
Posted Date: September 06, 2008

thanks for information...

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend