Search
Close this search box.

Uploading and Storing Image Path toDatabase and Image to Folder – Part 1

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 on how to display those images in a GridView and Repeater control. See this example.

This article is part of the GWB Archives. Original Author: Vinz`Blog

Related Posts