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
- The normal file up loader requires a button to upload the image and hence increases the operation of user.
- The Page reloads while the image is uploaded
- Does not provide loading message in built special logic has to be written.
- Same OLD Look.
Pros of AJAX ASYNC File Uploader
- The AJAX ASYNC File Uploader does not require an additional button to upload the file.
- The page will not reload while uploading or after uploading
- 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)
- Gives a new look to the uploader.
Objective
- Understanding the AJAX ASYNC File Uploader
- Understanding the Important properties used to upload a file using AJAX ASYNC Uploader
- 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" />
- 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.
- 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.
- 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.
- ThrobberID = This property will contain the ID of the Image that will show the loading progressbar while a heavy file is uploaded.
- 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
- Create an Empty website in Visual Studio 2010
- Add a New Folder named Images.
- Now we need to add AJAX Control Tool Kit.
- To Download the AJAX Control Toolkit please visit :- http://ajaxcontroltoolkit.codeplex.com/
- Unzip the File into a folder.
- 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
- 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.
- 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.
- You will get the following UI (Check the 2nd Screen)
- 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.
- 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)
- 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:-