Insert Image into Folder and Database

File Upload control enables users to upload file to web application. After the file is uploaded, user can store the file in system. Normally,user store the file either on the file system or in a database. I had explain both approach below.

Download source code and script here.

 

Save into Folder :-

Here, I will explain how you can upload images to an application by using the AsyncFileUpload file upload control. I already explain file upload in my previous article, but this will upload only images, allowed extension were (gif,png,jpg,jpeg).

HTML mark up looks like below :-

<div>

 <cc1:ToolkitScriptManager runat="Server" EnablePartialRendering="true" ID="ScriptManager1" />

 <cc1:AsyncFileUpload ID="afuUpload" OnUploadedComplete="afuUpload_UploadedComplete"

     OnUploadedFileError="afuUpload_UploadedFileError" runat="server" OnClientUploadComplete="uploadComplete"

     Width="400px" UploaderStyle="Modern" UploadingBackColor="#CCFFFF" ThrobberID="myThrobber" />

 <asp:Label runat="server" ID="myThrobber" Style="display: none;">

     <img align="absmiddle" alt="" src="Images/uploading.gif" />

 </asp:Label>

 <div style="border-style: solid; display: none; width: 350px" id="dvFileInfo">

   <asp:Label ID="lblStatus" Font-Bold="true" runat="server" Text="Status:-" />

   <asp:Label ID="lblSuccess" ForeColor="Green" runat="server" /><br />

  </div>

 <div style="border-style: solid; display: none; width: 350px" id="dvFileErrorInfo">

   <asp:Label ID="lblErrorStatus" Font-Bold="true" runat="server" Text="Status:-" />

   <asp:Label ID="lblError" ForeColor="Red" runat="server" /><br />

 </div>

</div>

 

AsyncFileUpload has javascript event named OnClientUploadComplete in this I am make validation for only uploaded images extension files. And also display whether images uploaded successfully or not.  One more event named OnClientUploadError, is used if file fail to upload images. Javascript markup looks like below :-

function uploadError(sender, args) {

            //Good practice to put try,catch block. it will avoid javascript error at window status.

  try

  {

    $get("dvFileErrorInfo").style.display='block';

    $get("dvFileInfo").style.display='none';

    $get("<%=lblError.ClientID%>").innerHTML = "File Not Uploaded" + args.get_errorMessage();

  }

  catch(e)

  {

    alert(e.message);

  }

}

 

function uploadComplete(sender, args) {

try

{

  var fileExtension=args.get_fileName();

  var gif =fileExtension.indexOf('.gif');

  var png =fileExtension.indexOf('.png);

  var jpg=fileExtension.indexOf('.jpg);

  var jpeg=fileExtension.indexOf('.jpeg);

 

  if(gif > 0 || png > 0 || jpg > 0 || jpeg > 0)

  {

    $get("dvFileInfo").style.display='block';

    $get("dvFileErrorInfo").style.display='none';

    $get("<%=lblSuccess.ClientID%>").innerHTML = "File Uploaded Successfully";

  }

  else

  {

    $get("dvFileErrorInfo").style.display='block';

    $get("<%=lblError.ClientID%>").innerHTML = "Allowed File extension are {.gif,.png,.jpg,.jpeg} supported";

    $get("dvFileInfo").style.display='none';

    return;

  }

}

catch(e)

{

  alert(e.message);

}     

}

above code is very simple, I am validating file extension with help of get_fileName() property of args, where I will get file name and indexOf() method is used where given file extension is valid or not.

For saving into folder, I will use AsyncFileUpload event OnUploadedComplete. I am validating and saving into given folder. Also used OnUploadedFileError if error occured while uploading file. Source code looks below :-

public void afuUpload_UploadedComplete(object sender, AsyncFileUploadEventArgs e)

    {

        try

        {

            string savePath = MapPath("~/Images/" + Path.GetFileName(e.filename));

 

            /*Validation for file extension*/

            bool gif =Path.GetExtension(e.filename).Contains(".gif");

            bool png =Path.GetExtension(e.filename).Contains(".png");

            bool jpg =Path.GetExtension(e.filename).Contains(".jpg");

            bool jpeg =Path.GetExtension(e.filename).Contains(".jpeg");

            if (gif || png || jpg || jpeg)

            {

                afuUpload.SaveAs(savePath);

            }

            else

            {

                return;

            }         

        }

        catch (Exception ex)

        {

            throw ex;

        }

    }

 

    public void afuUpload_UploadedFileError(object sender, AsyncFileUploadEventArgs e)

    {

        //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "error", "top.$get(\"" + lblErrorStatus.ClientID + "\").innerHTML = 'Error: " + e.statusMessage + "';", true);

    }

If give file is valid then it will upload images into Images folder inside application.

output looks like below :-

 

suc

 

Save into Database :-

File uploading into database is bit a complicated then file upload into folder. As in this one, we have create an table with datatype as image.

I created an table named UserData for saving images into Database. Screen shots below :-

User

User has to give userID (which is unique name for each user) and image path to upload into DB.

Here I will be using AsyncFileUpload to upload file. I am using OnClientUploadComplete of javascript, to validate file extension to insert only images into database.  This will be validating before click on save button.

HTML mark up look like this one :-

<div>

   <cc1:ToolkitScriptManager runat="Server" EnablePartialRendering="true" ID="ScriptManager1" />

   <asp:UpdatePanel ID="UpdatePanel1" runat="server">

   <ContentTemplate>

      <table>

        <tr>

           <td>

              <asp:Label ID="Label1" runat="server" Text="User ID" />

            </td>

            <td>

              <asp:TextBox ID="txtUserID" runat="server" />

            </td>

         </tr>

         <tr>

           <td>

              <asp:Label ID="Label2" runat="server" Text="Upload Image" />

           </td>

           <td>

              <cc1:AsyncFileUpload ID="afuUpload" OnClientUploadComplete="uploadComplete" runat="server"

               Width="300px" UploaderStyle="Modern" UploadingBackColor="#CCFFFF" />

              <asp:Label runat="server" ID="myThrobber" Style="display: none;">

               <img align="absmiddle" alt="" src="Images/uploading.gif" />

              </asp:Label>

           </td>

          </tr>

          <tr align="center">

            <td>

               <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />

            </td>

          </tr>

      </table>

        <asp:Label ID="lblMsg" ForeColor="Red" runat="server" /><br />

      <asp:ObjectDataSource ID="User" TypeName="objUser" InsertMethod="InsertUserDetail"

             runat="server">

        <InsertParameters>

         <asp:ControlParameter Name="UserID" ControlID="txtUserID" PropertyName="Text" />

         <asp:ControlParameter Name="UserImage" ControlID="afuUpload" PropertyName="FileBytes" />

       </InsertParameters>

      </asp:ObjectDataSource>

   </ContentTemplate>

 </asp:UpdatePanel>

</div>

 

AsyncFileUpload, OnClientUploadComplete event used for validating file upload at javascript side is same as folder upload which  already explain above. So that part I has been skiped.

source code for saving into database look like below :-

protected void btnSave_Click(object sender, EventArgs e)

{

   try

   {

      /*Validation for file extension*/

      bool gif = Path.GetExtension(afuUpload.FileName).Contains(".gif");

      bool png = Path.GetExtension(afuUpload.FileName).Contains(".png");

      bool jpg = Path.GetExtension(afuUpload.FileName).Contains(".jpg");

      bool jpeg = Path.GetExtension(afuUpload.FileName).Contains(".jpeg");

 

      if (gif || png || jpg || jpeg)

      {

          User.Insert();

          lblMsg.Text = "File Upload Successfully";

          lblMsg.ForeColor = System.Drawing.Color.Green;

      }

      else

      {

          lblMsg.Text = "Valid File Extension allowed are {.gif,.png,jpg,.jpeg}";

          lblMsg.ForeColor = System.Drawing.Color.Red;

      }           

   }

   catch (Exception ex)

   {

       lblMsg.Text = "File Not Upload";

       lblMsg.ForeColor = System.Drawing.Color.Red;

    }

}

 

Class file objUser.cs looks like below :-

using System;

using System.Data;

using System.Data.SqlClient;

using System.Web.Configuration;

using System.Web.UI.WebControls;

 

/// <summary>

/// Summary description for objCustomer

/// </summary>

public class objUser

{

   private readonly string conStr;

   public objUser()

   {

      conStr = WebConfigurationManager.ConnectionStrings["MyBlogConnectionString"].ConnectionString;

   }

 

    public void InsertUserDetail(string UserID, byte[] UserImage)

    {

       SqlConnection con = new SqlConnection(conStr);

       SqlCommand cmd = new SqlCommand("InsertUserDetail", con);

       cmd.CommandType = CommandType.StoredProcedure;

       SqlParameter param = new SqlParameter();

       param.SqlDbType=SqlDbType.Image;

       param.ParameterName = "@UserImage";

       param.SqlValue = UserImage;

       cmd.Parameters.AddWithValue("@UserID", UserID);

       cmd.Parameters.Add(param);

 

       using (con)

       {

           con.Open();

           cmd.ExecuteNonQuery();

       }

   }

}

 

output looks like below one :-

Insert

 

I hope you like this article for Image upload into Folder and Database. Download link has been provided above to download source code and script .  In the next article I will provide how to display images from folder as well as from database. Like to have your feedback in this. Your feedback will improve my next articles.

 

Enchancement :-

1)  Uniqueness of user name has not been validated

2)  Functionality has been given primary consideration, UI design has been given secondary. Can improve design side.

No Comments