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"

 

I decided to write this example because this has been asked many times at the forums. In my previous article I have shown on how to Upload and Save the Images to Database, In this article I will show on how to upload and save the image to folder and path to database.

 

To get started, let’s create a simple database table for storing the Image information and path to the database. I this example I named the table as “ImageInfo” with the following fields below:

 

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

Now, in Visual Studio, let’s create a folder under the root application for storing the actual image. The folder structure would look something like this below:

Solution

  -Application Name

  -AppCode

  -AppData

  -ImageStorage   - //we will save the image in this folder

  -Default.aspx

  -web.config

 

After that we can now design our WebForm. For the simplicity of this demo, I just set up the form like below:

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Untitled Page</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:FileUpload ID="FileUpload1" runat="server" />

        <br />

        <asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />

    </div>

    </form>

</body>

</html>

 

Simple right? I just contain a single Button and a FileUpload control. The next step is to set up our connection string in the web.config file. See below markup:

 

<connectionStrings>

            <add name="DBConnection" connectionString="Data Source=SERVERNAME\SQLEXPRESS;Initial Catalog=SampleDB;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>

</connectionStrings>

 

 

Now let’s go ahead and switch to code behind file of the form and create the method for Uploading and saving the Images. Here are the code blocks below:

 

    private void StartUpLoad()

    {

        //get the file name of the posted image

        string imgName = FileUpload1.FileName.ToString();

        //sets the image path

        string imgPath = "ImageStorage/" + imgName;

        //then save it to the Folder

        FileUpload1.SaveAs(Server.MapPath(imgPath));

 

        //get the size in bytes that

        int imgSize = FileUpload1.PostedFile.ContentLength;

 

        //validates the posted file before saving

        if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")

        {

            if (FileUpload1.PostedFile.ContentLength > 5120) // 5120 KB means 5MB

            {

                Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('File is too big')", true);

            }

            else

            {

                //save the file

                //Call the method to execute Insertion of data to the Database

                ExecuteInsert(imgName, imgSize, imgPath);

                Response.Write("Save Successfully!");

            }

        }

    }

 

    private string GetConnectionString()

    {

        //sets the connection string from your web config file. "DBConnection" is the name of your Connection String

        return System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;

    }

 

    private void ExecuteInsert(string name, int size, string path)

    {

 

        SqlConnection conn = new SqlConnection(GetConnectionString());

        string sql = "INSERT INTO ImageInfo (ImageName, ImageSize, ImagePath) VALUES "

                    + " (@ImgName,@ImgSize,@ImgPath)";

        try

        {

 

            conn.Open();

            SqlCommand cmd = new SqlCommand(sql, conn);

            SqlParameter[] param = new SqlParameter[3];

 

            param[0] = new SqlParameter("@ImgName", SqlDbType.NVarChar, 50);

            param[1] = new SqlParameter("@ImgSize", SqlDbType.BigInt, 9999);

            param[2] = new SqlParameter("@ImgPath", SqlDbType.VarChar, 50);

 

            param[0].Value = name;

            param[1].Value = size;

            param[2].Value = path;

 

            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();

    }

 

 

Method Definitions:

 

StartUpload() – is a method where the we get the information of the posted file and save the actual image to the folder. It is also where we validate the upload file and the file size before we insert the file information in the database.

 

ExecuteInsert() – is a method that accepts three parameters which will be save in the database.

 

Running the code above will show a FileUpload control with a Button in the page for saving the image. The actual image will be stored in the folder that we have created above and the image information will be saved to database table as shown below:

 


 

That’s it! Hope you will find this example useful!


 

 

In my next example, I will show how to display those images in a GridView and Repeater control. See this example.

 

Posted on Sunday, August 2, 2009 4:58 PM ADO.NET , ASP.NET , C# | Back to top


Comments on this post: Uploading and Storing Image Path to Database and Image to Folder - Part 1

# re: Uploading and Storing Image Path toDatabase and Image to Folder - Part 1
Requesting Gravatar...
Very helpful.. How can Ipost my questions into it?
Left by Tina on Aug 17, 2009 12:09 AM

# re: Uploading and Storing Image Path to Database and Image to Folder - Part 1
Requesting Gravatar...
it's producing error,"IS NOT A VALID VIRTUAL PATH"
Left by Rupesh on Mar 25, 2010 1:26 PM

# re: Uploading and Storing Image Path to Database and Image to Folder - Part 1
Requesting Gravatar...
path is saved in database but images is not saved in folder..........
Left by Mohit on Apr 13, 2010 5:50 PM

# re: Uploading and Storing Image Path to Database and Image to Folder - Part 1
Requesting Gravatar...
It's very useful to me..

Nice to see this kind of postings.


Thanks.
Left by jeevan on Dec 09, 2010 7:20 AM

# re: Uploading and Storing Image Path to Database and Image to Folder - Part 1
Requesting Gravatar...
path is saved in database but images is not saved in folder.
so say that where is that folder
Left by s.nagaraju on May 05, 2011 6:15 PM

# re: Uploading and Storing Image Path to Database and Image to Folder - Part 1
Requesting Gravatar...
beautifu!!!! spent the whole night trying to make it right until this. it works fine. it was giving a problem with the alert on file size verification. files got posted but alert still showed "file too is big" I commented the verification and used the web config to control file size. Thanks for Helping Out.
Left by Ronny on Aug 07, 2011 5:23 PM

# re: Uploading and Storing Image Path to Database and Image to Folder - Part 1
Requesting Gravatar...
StuPiccName = UploadPic.FileName.ToString();
StuPicPath = "images/" + StuPiccName;
UploadPic.SaveAs(Server.MapPath(StuPicPath));
is my code but it not showing the name of the pic and not uploading the image to the folder
Left by ali niar on Feb 23, 2012 5:07 PM

# re: Uploading and Storing Image Path to Database and Image to Folder - Part 1
Requesting Gravatar...
great work bro...its working and working efficiently....!!
Left by gaurav on Mar 13, 2012 6:12 PM

# re: Uploading and Storing Image Path to Database and Image to Folder - Part 1
Requesting Gravatar...
Dim imgPath As String = "ImageStorage/" & imgName


FileUpload1.SaveAs(Server.MapPath(imgPath))
Image1.ImageUrl = "~/" & imgPath

The image get uploaded into the folder,but the database does not store the path
Left by lucky on Apr 23, 2012 11:51 PM

# re: Uploading and Storing Image Path to Database and Image to Folder - Part 1
Requesting Gravatar...
Dim imgPath As String = "ImageStorage/" & imgName

'then save it to the Folder

FileUpload1.SaveAs(Server.MapPath(imgPath))
Image1.ImageUrl = "~/" & imgPath


I have aproblem with this code.The image got stored into the folder but the database is not storing the path..

Please help me with the codes..
Thanks in advance..
Left by lucky on Apr 23, 2012 11:53 PM

# re: Uploading and Storing Image Path to Database and Image to Folder - Part 1
Requesting Gravatar...
Dim imgPath As String = "ImageStorage/" & imgName

'then save it to the Folder

FileUpload1.SaveAs(Server.MapPath(imgPath))
Image1.ImageUrl = "~/" & imgPath


I have aproblem with this code.The image got stored into the folder but the database is not storing the path..

Please help me with the codes..
Thanks in advance..
Left by lucky on Apr 23, 2012 11:53 PM

# re: Uploading and Storing Image Path to Database and Image to Folder - Part 1
Requesting Gravatar...
I know how to save an image to a folder using the fileupload control with the saveas method. But I to take an image from the image control and save it to a file without using the fileupload control n save it in folder
Left by Kiran Solkar on May 22, 2012 2:39 PM

# re: Uploading and Storing Image Path to Database and Image to Folder - Part 1
Requesting Gravatar...
u post image file only can i get any file store in database code
thanks
Left by kishore on Jul 05, 2012 1:49 PM

# re: Uploading and Storing Image Path to Database and Image to Folder - Part 1
Requesting Gravatar...
Thank you...Thank you so much! I've been searching like 2 days for this solution. This is so helpful for me.
Left by Nandar Aung on Aug 03, 2012 11:05 PM

# re: Uploading and Storing Image Path to Database and Image to Folder - Part 1
Requesting Gravatar...
Thank u very much,this article was really helpfull for my project.

but can u tell me how to dispay the images who's path is saved in database aand image is stord in app. folder and show the image in gridview
Left by Pranjal Mishra on Oct 10, 2012 2:08 AM

# re: Uploading and Storing Image Path to Database and Image to Folder - Part 1
Requesting Gravatar...
Sorry, but the ContentLength is in Byte and not in kb, so the below line is incorrect :

if (FileUpload1.PostedFile.ContentLength > 5120) // 5120 KB means 5MB
The true is : 5120 mean 5120 byte or 5 kb
Left by Shamel on Oct 17, 2012 8:23 PM

# re: Uploading and Storing Image Path to Database and Image to Folder - Part 1
Requesting Gravatar...
easy to use......very useful...really acknowledgeable!!!!!!!!!!!
Left by Shivani on Jan 22, 2013 4:06 PM

# re: Uploading and Storing Image Path to Database and Image to Folder - Part 1
Requesting Gravatar...
INSERT query error: Implicit conversion from data type varchar to varbinary is not allowed. Use the CONVERT function to run this query.

I am getting this error message at this point:

catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);

what can be done to correct this??
Left by Charles Otieno on Jan 31, 2013 3:02 PM

# re: Uploading and Storing Image Path to Database and Image to Folder - Part 1
Requesting Gravatar...
@Charles Otieno,

Double check the datatype you use in your database. Make sure that the datatype from your code match with the datatype from your field in your database. So in this case change varbinary to varchar datatype in your database field.
Left by Vinz on Feb 01, 2013 12:23 AM

comments powered by Disqus

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