Upload Image using AJAX ASYNC FILE Uploader in Database.

Raj.Trivedi
Posted by in ASP.NET AJAX category on for Intermediate level | Points: 250 | Views : 27175 red flag

Hello Team,

In this article we will see how we can use the AJAX Async Uploader to upload images to the folder and save the path in database.

Introduction


Hello Friends,

Today in this article we will see how we can upload files using AJAX Async File Uploader.Now there comes a question in mind why to use AJAX Async Uploader and not the reqular one.

Cons of Normal File Uploader

  1. The normal file up loader requires a button to upload the image and hence increases the operation of user.
  2. The Page reloads while the image is uploaded
  3. Does not provide loading message in built special logic has to be written.
  4. Same OLD Look.
Pros of AJAX ASYNC File Uploader

  1. The AJAX ASYNC File Uploader does not require an additional button to upload the file.
  2. The page will not reload while uploading or after uploading
  3. You just need a GIF Image to notify the User if a Heavy File is uploaded.This image can be bound to the throbber property of the Uploader (Explained further in the article)
  4. Gives a new look to the uploader.



Objective


  1. Understanding the AJAX ASYNC File Uploader
  2. Understanding the Important properties used to upload a file using AJAX ASYNC Uploader
  3. Method to Save the File.

Before we get our hands on the code.Let us look into the properties of the AJAX ASYNC Uploader.


<asp:AsyncFileUpload ID="imageuploader" OnClientUploadComplete="UploadSuccess"OnClientUploadError="UploadFail" CompleteBackColor="White" Width="200" runat="server" UploaderStyle="Modern"
            UploadingBackColor="#CCFFFF" ThrobberID="loader" OnUploadedComplete="fileUploadComplete" />


  1. OnClientUploadComplete= This event will fire after the image has been uploaded successfully.As the name suggest it is a Client Side Event.This event will contain Javascript function.
  2. OnClientUploadError = This event will fire if the image  uploaded has failed.As the name suggest it is a Client Side Event.This event will contain Javascript function.
  3. UploaderStyle = This will actaully give the new look to the Uploader.There are only 2 options i.e. Modern and Traditional. Modern will gives new look.
  4. ThrobberID = This property will contain the ID of the Image that will show the loading progressbar while a heavy file is uploaded.
  5. OnUploadedComplete = This is the most important property, this property will actually contain the logic for uploading the file to the server.
Note :- All the functions that are attached or assigned to the property should be Case sensitive.





Using the code


  1. Create an Empty website in Visual Studio 2010 
  2. Add a New Folder named Images.
  3. Now we need to add AJAX Control Tool Kit.
  4. To Download the AJAX Control Toolkit please visit :- http://ajaxcontroltoolkit.codeplex.com/
  5. Unzip the File into a folder.
  6. Now its time to embed into Our Website so now go to Tool Box -> Right Click in Empty Space -> Select Add Tab -> Name it as AJAX Control Tool KIT and Click OK
  7. Then Go into the Tab that we have created and right click in the area and Select Choose Items and Browse for AJAX DLL which we have unzipped earlier.Check the Screen.
  8. Once the AJAX is added to the toolbox now drag and drop a ToolKIT Script Manager and then drag and drop an AJAX ASYNC FILE Uploader.
  9. You will get the following UI (Check the 2nd Screen)
  10. Now once the control is added and everything seems fine.Now we have to write the code,that is writing the function of OnUploadedComplete in code behind.
  11. In order to do it go to the event section of the control and you will get UploadedComplete you just need to double click on that event you will go to Code behind where you can write the code.(Check the 3rd Screen)
  12. Finally we are ready to code the server side.Check the code.

Step  7 :- Adding AJAX To Website




Step 9 :- UI



Step 11:-




Tables and Stored Procedure
USE [DNF]
GO

/****** Object:  Table [dbo].[Images]    Script Date: 07/02/2013 22:29:13 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Images](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Imagepath] [varchar](max) NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO


USE [DNF]
GO

/****** Object:  StoredProcedure [dbo].[GetImages]    Script Date: 07/02/2013 22:29:20 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

create proc [dbo].[GetImages]
as
begin
select * from Images
end
GO

USE [DNF]
GO

/****** Object:  StoredProcedure [dbo].[InsertImages]    Script Date: 07/02/2013 22:29:37 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

create proc [dbo].[InsertImages]
(
@Imagepath varchar(max)
)
as
begin
insert into Images(Imagepath) values(@Imagepath)
end
GO
 HTML Mark UP
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AjaxAsyncUploader.aspx.cs"
    Inherits="AjaxAsyncUploader" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        // This function will execute after file uploaded successfully
        function UploadSuccess() {
            document.getElementById('<%=errdesc.ClientID %>').innerHTML = "File Uploaded Successfully to Images Folder";
        }
        // This function will execute if file upload fails
        function UploadFail() {
            document.getElementById('<%=errdesc.ClientID %>').innerHTML = "File upload Failed.Please Try Again.";
        }
</script>
</head>
<body>
    
    <form id="form1" runat="server">
    <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
    </asp:ToolkitScriptManager>
    <div align="center">
        <asp:AsyncFileUpload ID="imageuploader" OnClientUploadComplete="UploadSuccess" OnClientUploadError="UploadFail"
            CompleteBackColor="White" Width="200" runat="server" UploaderStyle="Modern"
            UploadingBackColor="#CCFFFF" ThrobberID="loader" OnUploadedComplete="fileUploadComplete" />
        <br />
        <asp:Image ID="loader" runat="server" ImageUrl="~/Images/Teddy Bear Loading.gif" Height="100" Width="300" />
        <asp:Label ID="errdesc" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>
//Code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.SqlClient;
using System.Data;

public partial class AjaxAsyncUploader : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }


    protected void fileUploadComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
    {
        try
        {
            // Getting the File Name 
            string filename = System.IO.Path.GetFileName(imageuploader.FileName);

            // Setting the path to upload Images

            imageuploader.SaveAs(Server.MapPath("Images/") + filename);

            // Storing the relative path to store into images
            string Imagepath = "~/Images/" + filename;
            // Opening the Connection for SQL Injection
            SqlConnection con = new SqlConnection("Data Source=AG-KKC;Initial Catalog=DNF;Persist Security Info=True;User ID=sa;Password=sqluser");
            con.Open();
            SqlCommand insertpathindb = new SqlCommand("InsertImages",con);
            insertpathindb.CommandType = CommandType.StoredProcedure;
            insertpathindb.Parameters.AddWithValue("@Imagepath",SqlDbType.VarChar).Value= Imagepath;
            insertpathindb.ExecuteNonQuery();
            con.Close();
            
        }
        catch (Exception ex)
        {
            
        }
    }
}

Explanation of Functions assigned to the properties

Property Name :- OnClientUploadComplete
Assigned Function :- UploadSuccess
Description :- In this we are just displaying the message in the label stating that file is uploaded if the upload is successful.This is a Javascript function

Property Name :- OnClientUploadError 
Assigned Function :- UploadFail
Description :- In this we are just displaying the message in the label stating that file uplaod has failed if there is any error.This is a Javascript function


Property Name :- OnUploadedComplete
Assigned Function :- fileUploadComplete
Description :- In this we actually defining the logic to upload the Images using Server.Mappath and using the SAVEAS method to save the image in the folder and then performing SQL Insert Execution.

Final Output 


Image Uploading and Loading Notification shown




Image Uploaded Successfull






Conclusion


It is quite useful when you want to upload images quickly and permanence matters.

Reference


More Properties can be read on:-



Page copy protected against web site content infringement by Copyscape

About the Author

Raj.Trivedi
Full Name: Raj Trivedi
Member Level:
Member Status: Member,MVP
Member Since: 6/16/2012 2:04:41 AM
Country: India
Regard's Raj.Trivedi "Sharing is Caring" Please mark as answer if your Query is resolved
http://www.dotnetfunda.com/profile/raj.trivedi.aspx
Raj Trivedi i.e. me started my career as Support Professional and then moved on the Software development eventually reached at these skills Software Development | Enthusiastic Blogger | Content Writer | Technical Writer | Problem Solver | Lecturer on Technology Subjects | Runnerup Award Winner on www.dotnetfunda.com and firm believer in Sharing as a way of Caring Yet this much achieved its still a long way to go and there is biggest dream lying to be one of the best entrepreneurs of India in Technology Department. The Dream has just started and i hope it follows. Highlights are mentioned in details in my profile at http://in.linkedin.com/pub/raj-trivedi/30/61/b30/

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)