Geeks With Blogs

News

Microsoft MVP


Moderator at CodeASP.NET


Quiz Master




free counters
Free counters
Added on January 19,2012


Follow Me @vmsdurano

A bit About Me



Disclaimer
The opinions expressed herein are my own personal opinions and does not represent the opinions of my employers. Nor does it represent the opinion of my dog, because I don’t have one.


Vinz' Blog (ProudMonkey) "Code, Beer and Music ~ my way of being a programmer"

This example demonstrates how to upload image using the FileUpload control and store the uploaded file in the database in binary format.

STEP 1: Creating the Database.

The following are the basic steps on how to create a simple database in the Sql Server:

  1. Launch Sql Server Management Studion Express and then connect
  2. Expand the Databases folder from the Sql Server object explorer
  3. Right click on the Databases folder and select “New Database”
  4. From the pop up window, input the database name you like and click add
  5. Expand the Database folder that you have just added
  6. Right click on the Tables folder and select “New Table”
  7. Then add the following fields below:

1(1)

 

Note: in this demo, I set the Id to auto increment so that the id will be automatically generated for every new added row. To do this select the Column name “Id” and in the column properties set the “Identity Specification” to yes.

Then after adding all the necessary fields, name your Table the way you like. Note that in this demo I name it “TblImages”

STEP 2: Setting up the WebForm (UI)

For the simplicity of this demo, I set up the UI like this below:

2

STEP3: Setting up the Connection String

In your web.config file set up the connection string there as shown below:

  <connectionStrings>
    <add name="MyConsString" connectionString="Data Source=YourServerName;
                             Initial Catalog=MyDatabase;
                             Integrated Security=SSPI;"
                             providerName="System.Data.SqlClient" />
  </connectionStrings>
 

Note: MyConsString is the name of the Connection string that we can use as a reference in our codes for setting the connection string later.

STEP 4: Storing the binary image to database.

Here are the code blocks below:

    private void StartUpLoad()
    {

        //get the image file that was posted (binary format)
        byte[] theImage = new byte[FileUpload1.PostedFile.ContentLength];
        HttpPostedFile Image = FileUpload1.PostedFile;
        Image.InputStream.Read(theImage, 0, (int)FileUpload1.PostedFile.ContentLength);
        int length = theImage.Length; //get the length of the image
        string fileName = FileUpload1.FileName.ToString(); //get the file name of the posted image
        string type = FileUpload1.PostedFile.ContentType; //get the type of the posted image
        int size = FileUpload1.PostedFile.ContentLength; //get the size in bytes that
        if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
        {
            //Call the method to execute Insertion of data to the Database
            ExecuteInsert(theImage, type, size, fileName, length);
            Response.Write("Save Successfully!");
        }
    }

    public string GetConnectionString()
    {
        //sets the connection string from your web config file "ConnString" is the name of your Connection String
        return System.Configuration.ConfigurationManager.ConnectionStrings["MyConsString"].ConnectionString;
    }

    private void ExecuteInsert(byte[] Image, string Type, Int64 Size, string Name, int length)
    {
        SqlConnection conn = new SqlConnection(GetConnectionString());
        string sql = "INSERT INTO TblImages (Image, ImageType, ImageSize, ImageName) VALUES "

                    + " (@img,@type,@imgsize,@imgname)";
        try
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);
            SqlParameter[] param = new SqlParameter[4];

            param[0] = new SqlParameter("@img", SqlDbType.Image, length);
            param[1] = new SqlParameter("@type", SqlDbType.NVarChar, 50);
            param[2] = new SqlParameter("@imgsize", SqlDbType.BigInt, 9999);
            param[3] = new SqlParameter("@imgname", SqlDbType.NVarChar, 50);
 
            param[0].Value = Image;
            param[1].Value = Type;
            param[2].Value = Size;
            param[3].Value = Name;
 
            for (int i = 0; i < param.Length; i++)
            {
                cmd.Parameters.Add(param[i]);
            }

            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Insert Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            conn.Close();
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        StartUpLoad();
    }

 

StartUpload() is method that gets all the necessary information from the uploaded file such as the image length, size, type, filename and the image itself in a binary format.

GetConnectionString() is a method that returns the connection string that was set up from the web.config file.

ExecuteInsert() is a method that will executes the insertion of data to the database. This method takes all the necessary data to be inserted in the database.

As you can see the code above is pretty straight forward and self explanatory.

Check out my next example about "

Displaying Image to Image Control based on User Selection in ASP.NET

"

I hope you will find this example useful!

Posted on Thursday, April 23, 2009 11:13 AM ADO.NET , ASP.NET , C# | Back to top


Comments on this post: Uploading and Storing Images to Database in ASP.NET

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
jgkljkljgldfkg

Left by qw on Jun 29, 2009 3:39 AM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
hai ,the code is good and very simple ,nice if u cud write one for downloading too..
thanks
Left by darsana on Jun 30, 2009 3:01 AM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
this produced a lot of errors called this
using System.Data.SqlClient; but still this

------ Build started: Project: C:\WebSite4\, Configuration: Debug Any CPU ------
Validating Web Site
Building directory '/WebSite4/'.

C:\WebSite4\Default.aspx.cs(47,49): error CS0103: The name 'SqlDbType' does not exist in the current context
C:\WebSite4\Default.aspx.cs(48,50): error CS0103: The name 'SqlDbType' does not exist in the current context
C:\WebSite4\Default.aspx.cs(49,53): error CS0103: The name 'SqlDbType' does not exist in the current context
C:\WebSite4\Default.aspx.cs(50,53): error CS0103: The name 'SqlDbType' does not exist in the current context
C:\WebSite4\Default.aspx.cs(62,31): error CS0103: The name 'CommandType' does not exist in the current context
Validation Complete
========== Build: 0 succeeded or up-to-date, 1 failed, 0 skipped ==========
Left by zpupster on Jul 31, 2009 11:44 AM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
it is working now, i did not have :
using System.Data
using System.Data.SqlClient
at the top couple of typos in the connection string

thanks for this
Left by zpupster on Jul 31, 2009 4:23 PM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx Thanx
Left by sharad on Sep 12, 2009 9:37 AM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
how to store the image to database from imagecontol event in asp.net
Left by dinakaran on Oct 15, 2009 11:45 PM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
nice article it was very helpful for me
Left by kranti on Dec 06, 2009 5:09 AM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
Is there any way to upload multiple Images at a time
Left by krishy on Dec 28, 2009 8:15 AM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
how does one link this to a specific user?

Left by hi on Feb 02, 2010 6:36 PM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
hey.. thnkx ur code is working... thnkx alot

can u post a code for fetching the image into a webform and crystal report.
Left by Ramanjot on Aug 13, 2010 3:55 PM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
i used above code and run without any error but it is not able to insert image in database . when i clicked on button than it simply refresh the browser and lives as it is. if i missed any thing than please clearly deal that .......................
Left by santosh on Jul 20, 2011 5:42 AM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
@santosh,

The easiest thing that you can do is to debug your codes and step into it so that you'll figure out why is that happening.
Left by Vinz on Jul 21, 2011 1:39 PM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
Incorrect syntax near the keyword 'file'.....
Left by sianing on Aug 03, 2011 4:58 PM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
Thank you very much for your great post.





Left by Capt on Dec 20, 2011 1:11 PM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
Exception was unhandled by user code

Insert Error: Invalid object name tblImages
Left by Mukund.Potdar on Jan 01, 2012 9:07 PM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
I am sorry
My Mistake was i have not written table name correctly, Finally i thank a lot for providing this code. At the end i have a question when i upload image in facebook i see loading animation can we do same in asp.net do you have and idea, Thank you
Left by Mukund.Potdar on Jan 01, 2012 9:11 PM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
thank u so much ...it really helped a lot
Left by ranjan on Jan 13, 2012 7:40 PM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
Great ! Very Helpful for me .. Thanks Bro ....
Left by Muhammad Faisal on Mar 25, 2012 8:21 AM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
above code is working fine.

Sanju

thank a lot
Left by SANJEEV SRIVASTAVA on Apr 19, 2012 5:40 PM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
Thank's

You saved my time and efforts
Left by Swapnil Godambe on Apr 23, 2012 3:50 PM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
Fine thanks for sharing
Left by Prasanna on May 08, 2012 3:41 PM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
Good one, thanks a lot
Left by tunde.net on May 10, 2012 4:59 PM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
plz tell about generic handler
Left by anjna on May 24, 2012 10:33 PM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
plz tell me about handler file
Left by anb on May 24, 2012 10:49 PM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
Simply awesome
Left by suresh on Jun 01, 2012 3:10 PM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
thanks。 perfect
Left by starter on Aug 24, 2012 9:38 AM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
Would u mind if the code of (Uploading and Storing Images to Database in ASP.NET)
didnot using sql db ,Because I am using Microsoft Access db so, I hope to helpe me ,,,,,
Thank u
Left by Waleed on Sep 01, 2012 2:08 AM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
FileUpload1.SaveAs ("D://ASP.Net//" + FileUpload1.FileName);
Label2 .Text ="File Uploaded Successfully";
}
else
{
Label2 .Text ="No Uploaded File";
}
Left by Akash on Sep 27, 2012 1:57 PM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
Thanks for the code..it works well..just a suggestion..
use only the execute command inside the try block..all others like connection string,command,parameters,the for statement etc can be kept just above the try statement..otherwise a single image will be inserted several times in the table..thanks once again..
Left by .net beginner on Oct 05, 2012 3:38 AM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
Server Error in '/sarkaut_tv' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Left by sarkaut on Oct 08, 2012 5:26 PM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
why <<SqlDbType>>> error?????????please soon response
Left by sarkaut on Oct 08, 2012 9:54 PM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
I saw ur all image file upload tutorials ..reallly meaningful and sensible.complete understanding........good work.really acknowledgeable
Left by shivani on Jan 22, 2013 4:47 PM

# re: Uploading and Storing Images to Database in ASP.NET
Requesting Gravatar...
This article is very useful. please help me in saving the image into database from image control
Left by SreeVidya on Feb 06, 2013 3:32 PM

comments powered by Disqus

Copyright © Vincent Maverick Durano | Powered by: GeeksWithBlogs.net | Join free