Ajax Dragndrop PDF
Ajax Dragndrop PDF
Ajax Dragndrop PDF
Home ASP. NET MVC SQL SERVER AJAX JQUERY JAVASCRIPT INTERVIEW QUESTIONS About Us Cont act Us
Drag & drop to upload multiple files using AjaxFileUpload
like Facebook in asp.net
Introduction: In previous articles i explained How to Get city, state and country based on zip
code using Google map API in asp.net and Ajax AutoCompleteExtender control example using
web service and How to upload file and create Zip file in asp.net and How to check and
validate file extension before uploading a file through FileUpload control and How to upload,
download and delete files from GridView
In this article I am going to explain How
to upload multiple files/images by drag
and drop or by browsing/selecting like
Facebook using AjaxFileUpload control
of AJAX in asp.net. We will create an
asp.net application having the
functionality of uploading multiple
images to create album and saving the
path of each image in table of SqlServer
database. Then Uploaded images will be binded to DataList data control to show as album.
Implementation: Create the Database in sql server e.g. "MyDataBase" and design the table
in that database as shown below and name it TB_IMG
Column Data Type
IMAGE_ID int(Primary Key i.e. Set identity property=true)
IMAGE_NAME varchar(200)
IMAGE_PATH varchar(500)
Now in web.config file add the connectionstring under <configuration> tag
<connectionStrings>
<add name="conStr" connectionString="Data Source=LocalServer;Initial
Catalog=MyDataBase;Integrated Security=True"/>
</connectionStrings>
Note: Replace the Data Source ans Initial Catalog as per your application.
In the design page (.aspx) place a ScriptManager control from the AJAX
Extensions category of Visual studio toolbox.
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
Place AjaxFileUpload control from the Ajax Control Toolkit. For this you need to install Ajax
control toolkit to use any Ajax control like AjaxFileUpload control. If you have not installed
or dont know how to install Ajax Control Toolkit then read my article "How to install Ajax
Control Toolkit in Visual Studio?"
Also place a button control to show the album and create a folder in root directory and name
it Album
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<fieldset style="width:600px;">
<legend>AjaxFileUpload control example to upload multiple files by Drag and
Drop</legend>
<table style="width:100%;">
<tr>
Click on image to enlarge
Free updates
into your Inbox
Enter your email... Subscribe
Follow us on:
3 tier architecture Asp.Net ( 2 )
Ajax Accordion ( 1 )
Ajax AutoCompleteExtender ( 2 )
Ajax CascadingDropDown ( 1 )
Ajax ModalPopupExtender ( 3 )
Ajax TabContainer ( 1 )
AjaxFileUpload ( 1 )
Asp.Net Error Solutions ( 8 )
Change Password ( 1 )
CheckBoxList ( 8 )
CompareValidator ( 1 )
Contact Us form ( 1 )
Crystal Reports ( 1 )
Cursor ( 2 )
CustomValidator ( 3 )
DataBase Backup ( 2 )
DataList ( 5 )
DIFFERENCES ( 6 )
DropDown Menu ( 3 )
DropDownList ( 13 )
Export GridView ( 4 )
FileUpload Control ( 23 )
GridView Examples ( 44 )
Interview Questions Answers ( 15 )
JOINS in SQL SERVER ( 3 )
Jquery ( 13 )
Jquery Validations ( 6 )
LINQ ( 1 )
ListBox ( 3 )
Login Form/Page ( 3 )
MessageBox ( 4 )
CATEGORIES
<td width="20%">Upload Album</td>
<td>
<asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
onuploadcomplete="AjaxFileUpload1_UploadComplete"/>
</td>
</tr>
<tr><td colspan="2">
<asp:DataList ID="dlImages" runat="server" RepeatColumns="4"
RepeatDirection="Horizontal" BackColor="White" BorderColor="#999999"
BorderStyle="None" BorderWidth="1px" CellPadding="3">
<AlternatingItemStyle BackColor="#DCDCDC" />
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
<ItemStyle BackColor="#EEEEEE" ForeColor="Black" />
<ItemTemplate>
<table border="0" style="border-bottom-color:#60BAEA;border-top-
color:#60BAEA;border-left-color:#60BAEA;border-left-color:#60BAEA;" cellspacing="5"
>
<tr>
<td align="center">
<asp:Image ID="img" runat="server" align="center" BorderStyle="Solid"
BorderColor="#e0ddd7" BorderWidth="2" Height="150" ImageUrl='<%#
DataBinder.Eval(Container.DataItem, "IMAGE_PATH") %>'
Width="150px" />
</td>
</tr>
</table>
</ItemTemplate>
<SelectedItemStyle BackColor="#008A8C" Font-Bold="True"
ForeColor="White" />
</asp:DataList>
</table>
<center><asp:Button ID="btnViewAlbum" runat="server" Text="View Album"
OnClick="btnViewAlbum_Click" /> </center>
</fieldset>
Have you noticed the line <%@ Register Assembly="AjaxControlToolkit"
Namespace="AjaxControlToolkit" TagPrefix="asp" %> added automatically next
to the very first line in the design page. Actually it registers the Ajax Control on
placing AjaxFileUpload control on design page.
C#.Net Code to upload multiple files by drag and drop using AjaxFileUpload control
First include following namespaces:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
Then write the code on UploadComplete event of AjaxFileUpload control as:
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindAlbumDataList();
}
}
protected void AjaxFileUpload1_UploadComplete(object sender,
AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
string filePath = string.Empty;
try
{
filePath = (Server.MapPath("~/Album/") + Guid.NewGuid() +
System.IO.Path.GetFileName(e.FileName));
AjaxFileUpload1.SaveAs(filePath);
string strFile = filePath.Substring(filePath.LastIndexOf("\\"));
string strFileName = strFile.Remove(0, 1);
string strFilePath = "~/Album/" + strFileName;
SqlCommand cmd = new SqlCommand("Insert into TB_IMG
(IMAGE_NAME,IMAGE_PATH) values (@IMAGE_NAME,@IMAGE_PATH)", con);
cmd.Parameters.AddWithValue("@IMAGE_NAME", strFileName);
cmd.Parameters.AddWithValue("@IMAGE_PATH", strFilePath);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
cmd.Dispose();
}
catch (Exception ex)
{
Pop Up ( 4 )
RadioButtonList ( 3 )
RegularExpression Validation Control ( 3 )
Repeater ( 8 )
Send Emails ( 6 )
Transaction In SQL ( 1 )
Validation Controls ( 13 )
WCF SERVICES ( 2 )
XML ( 10 )
Lalit Raghuvanshi
I am a passionate
programmer and a Software
Engineer love blogging and
developing applications in
Microsoft Technologies.
View my complete profile
ABOUT ME
Encontre-nos no Facebook
Asp.net , Sql server, jquery &
javascript code snippets
3.839 pessoas curtiram Asp.net , Sql server, jquery &
javascript code snippets.
Curtir
POPULAR POSTS
Create registration form and send
confirmation email to new registered users
in asp.net | Activate or approve user
account by activation link in email address.
1
How to create Login page/form and check
username,password in asp.net using stored
procedure and sql server database
2
Asp.Net MVC 4 application to
Create,Read,Update,Delete and Search
functionality using Razor view engine and
Entity Framework
3
How to create and consume WCF Services
in asp.net ?
4
How to create 3 tier application in Asp.Net
C# to Insert,edit,update,bind and delete
data
5
Regex to check whether entered string is
numeric or not in Asp.net C#,VB
6
How to check whether a string is numeric
or not in Asp.net C#,VB
7
Bind,Save,Edit,Update,Cancel,Delete,Paging
example in GridView in asp.net C#
8
Date and Time formats in asp.net using
C#,VB.Net | Convert date time formats
9
May 2014 (2)
April 2014 (14)
March 2014 (3)
February 2014 (4)
January 2014 (8)
December 2013 (6)
November 2013 (13)
October 2013 (10)
BLOG ARCHIVE
Response.Write(ex.Message.ToString());
}
}
protected void BindAlbumDataList()
{
try
{
SqlCommand cmd = new SqlCommand("SELECT IMAGE_NAME,IMAGE_PATH FROM
TB_IMG", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dlImages.DataSource = dr;
dlImages.DataBind();
}
else
{
dlImages.DataSource = null;
dlImages.DataBind();
}
}
catch (Exception ex)
{
Response.Write("Error Occured: " + ex.ToString());
}
finally
{
con.Close();
}
}
protected void btnViewAlbum_Click(object sender, EventArgs e)
{
BindAlbumDataList();
}
Note: I have used Guid.NewGuid() to generate unique name for each image/file. GUID means
Gloabally Unique Identifier.
VB.Net Code to upload multiple files by drag and drop using AjaxFileUpload control
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<fieldset style="width:600px;">
<legend>AjaxFileUpload control example to upload multiple files by Drag and
Drop</legend>
<table style="width:100%;">
<tr>
<td width="20%">Upload Album</td>
<td>
<asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server"/>
</td>
</tr>
<tr><td colspan="2">
<asp:DataList ID="dlImages" runat="server" RepeatColumns="4"
RepeatDirection="Horizontal" BackColor="White" BorderColor="#999999"
BorderStyle="None" BorderWidth="1px" CellPadding="3">
<AlternatingItemStyle BackColor="#DCDCDC" />
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
<ItemStyle BackColor="#EEEEEE" ForeColor="Black" />
<ItemTemplate>
<table border="0" style="border-bottom-color:#60BAEA;border-top-
color:#60BAEA;border-left-color:#60BAEA;border-left-color:#60BAEA;" cellspacing="5"
>
<tr>
<td align="center">
<asp:Image ID="img" runat="server" align="center" BorderStyle="Solid"
BorderColor="#e0ddd7" BorderWidth="2" Height="150" ImageUrl='<%#
DataBinder.Eval(Container.DataItem, "IMAGE_PATH") %>'
Width="150px" />
</td>
</tr>
</table>
</ItemTemplate>
<SelectedItemStyle BackColor="#008A8C" Font-Bold="True"
ForeColor="White" />
</asp:DataList>
</table>
<center><asp:Button ID="btnViewAlbum" runat="server" Text="View Album"/>
</center>
September 2013 (13)
August 2013 (21)
July 2013 (27)
June 2013 (30)
May 2013 (41)
April 2013 (24)
March 2013 (43)
February 2013 (32)
Tweet
14
23
82
165
Gosto
Share
</fieldset>
First include following namespaces:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports AjaxControlToolkit
Then write the code on UploadComplete event of AjaxFileUpload control as:
Dim con As New
SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
BindAlbumDataList()
End If
End Sub
Protected Sub AjaxFileUpload1_UploadComplete(sender As Object, e As
AjaxFileUploadEventArgs) Handles AjaxFileUpload1.UploadComplete
Dim filePath As String = String.Empty
Try
filePath = (Server.MapPath("~/Album/") & Convert.ToString(Guid.NewGuid()) &
System.IO.Path.GetFileName(e.FileName))
AjaxFileUpload1.SaveAs(filePath)
Dim strFile As String = filePath.Substring(filePath.LastIndexOf("\"))
Dim strFileName As String = strFile.Remove(0, 1)
Dim strFilePath As String = "~/Album/" & strFileName
Dim cmd As New SqlCommand("Insert into TB_IMG (IMAGE_NAME,IMAGE_PATH)
values (@IMAGE_NAME,@IMAGE_PATH)", con)
cmd.Parameters.AddWithValue("@IMAGE_NAME", strFileName)
cmd.Parameters.AddWithValue("@IMAGE_PATH", strFilePath)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
cmd.Dispose()
Catch ex As Exception
Response.Write(ex.Message.ToString())
End Try
End Sub
Protected Sub BindAlbumDataList()
Try
Dim cmd As New SqlCommand("SELECT IMAGE_NAME,IMAGE_PATH FROM TB_IMG",
con)
con.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader()
If dr.HasRows Then
dlImages.DataSource = dr
dlImages.DataBind()
Else
dlImages.DataSource = dr
dlImages.DataBind()
End If
Catch ex As Exception
Response.Write("Error Occured: " + ex.ToString())
Finally
con.Close()
End Try
End Sub
Protected Sub btnViewAlbum_Click(sender As Object, e As EventArgs) Handles
btnViewAlbum.Click
BindAlbumDataList()
End Sub
Note: I have used Guid.NewGuid() to generate unique name for each image/file. GUID means
Gloabally Unique Identifier
There are some properties that can be helpful to us if we want to restrict the type of the file
to upload or set the maximum number of files that can be uploaded e.g:
<asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
AllowedFileTypes="jpg,jpeg,png,gif,bmp"
MaximumNumberOfFiles="5"
onuploadcomplete="AjaxFileUpload1_UploadComplete" />
AllowedFileTypes : Using the property AllowedFileTypes, we can restrict the types of files
which can be uploaded with the AjaxFileUpload control. E.g. we can prevent any file except
image files (files with the extensions jpeg, png, gif or bmp) from being uploaded
MaximumNumberOfFiles : Using this property we can limit the number of files which can be
uploaded. e.g. We can prevent a user from uploading more than 5 files.
Posted by Lalit Raghuvanshi
Labels: AJAX , AjaxFileUpload , ASP.NET , C#.Net , DataList , FileUpload Control , VB.Net
How to send mail
with multiple
attachments in
asp.net with ...
Send email to
multiple users
based on
CheckBox
selection ...
How to show
Validation
guidelines in web
forms using ...
How to return data
through Output
Parameter in
stored ...
Now over to you:
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like
button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on
stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned
for more technical updates. "
Drag & drop to upload multiple files using AjaxFileUpload like Facebook in asp.net
How to check whether a string is numeric or not in Asp.net C#,VB
Regex to check whether entered string is numeric or not in Asp.net C#,VB
JavaScript to enable/disable asp.net controls on textbox value change or typing text in
TextBox
Highlight or change row background color in Asp.net Repeater based on condition
You might also like:
RELATED POSTS
+23 Recommend this on Google
Replies
Reply
32 comments :
Sujit Singh September 11, 2013
its really nice one....
Reply
Lalit Raghuvanshi September 11, 2013
i am glad you like my post..keep reading..
Sujit Singh September 12, 2013
thank u sir...
viney September 23, 2013
i am getting error while upload files.. what to do now?
Lalit Raghuvanshi September 23, 2013
Hello viney..what type of error you are getting? please paste the details
here..i will help you to sort out the problem.
Replies
Reply
Replies
Reply
Replies
Reply
Replies
Reply
Anonymous September 13, 2013
I am getting this error Sys.Extended is undefined
Reply
Lalit Raghuvanshi September 13, 2013
Seems there is an error in your ajaxtoolkit. Can you please paste the full error
detail here so that i can help you sort out the error.
Kevin Oxtoby September 13, 2013
Looks good, will it allow me to do drag and drop of outlook emails?
Reply
Lalit Raghuvanshi September 13, 2013
Thanks Kevin.and sorry this article is for uploading multiple files..
Anonymous September 17, 2013
Hi I can show a server side error message using this controls? Means I have to check
some files that cannot save to the server. Currently its showing successful even files are
not saved on server.
Reply
Lalit Raghuvanshi September 18, 2013
Using the property AllowedFileTypes, we can restrict the types of files which
can be uploaded with the AjaxFileUpload control. E.g. we can prevent any file
except image files (files with the extensions jpeg, png, gif or bmp) from being
uploaded e.g.
Anonymous September 18, 2013
Thank you for your suggestion. I have to validate some files not only file type, so i have
to show failed message on server side. Any idea?
Reply
Daban Abdulla September 24, 2013
thank you ..... but when i run it it does not give me any error but when i want to upload
it does not do anything i mean when i click on the button it doesn't open any file upload
dialogbox
Reply
Lalit Raghuvanshi September 24, 2013
Hello Daban Abdulla..I think you are missing something in your code..so i
suggest you to recheck all of your code with this article and try once again..if
still you face error then let me know..i will try to sort out your issue..
Anonymous September 25, 2013
Replies
Reply
Replies
Reply
Replies
Reply
Hi, When i select multiple images it is uploading only one image
and for remaing images it is showing as pending
Reply
Lalit Raghuvanshi September 25, 2013
Hello..i suggest you to recheck you code and also try to debug the code so that
you can find the problem and resolve it.. if still you face error then let me
know..i will try to sort out your issue..
Ankamma Rao October 04, 2013
Hi sir..,
Thanks for giving this code.In this code small doubt sir,it will not show the file
attachment,t will show the black space. what i will do.
Reply
Ankamma Rao October 04, 2013
Hi sir..,
Thanks for giving this code.In this code small doubt sir,it will not show the file
attachment,t will show the black space. what i will do.
Reply
Ankamma Rao October 04, 2013
Hi sir..,
Thanks for giving this code.In this code small doubt sir,it will not show the file
attachment,t will show the black space. what i will do.
Reply
Lalit Raghuvanshi October 05, 2013
Hello Ankamma Rao..this article will allow you to upload multiple images at
once and then that images will get displayed in the DataList control..What
exactly you want?
Ajay Kajal October 09, 2013
hello sir,
can you provide code for uploading multiple image after resizing and after resizing
image it should be saved into root folder and in database only image name saved
Reply
Lalit Raghuvanshi October 09, 2013
Hi Ajay..you can read my articles:
How to resize image in Asp.net?
http://www.webcodeexpert.com/2013/04/how-to-resize-image-in-
aspnet.html
How to bind,upload,download,delete image files from the GridView in
asp.net using Sql Server as a back end database
http://www.webcodeexpert.com/2013/08/how-to-
binduploaddownloaddelete-image.html
After reading these articles you will be able to fulfill your requirement..I will
also create an articles as per your requirement and upload that very soon..so
stay connected and keep reading :)
Replies
Reply
Replies
Reply
Manvendra Patel November 14, 2013
i want to save some other value remaning image name & image path ,but i am not able
to save when we use any asp control value .plz help me
Reply
Jitendra Gangwar December 05, 2013
i want to save a another textbox value but retrive textbox value is empty in
onuploadcomplete method. plz help me
Reply
Bebins December 12, 2013
Hi i set MaximumNumberOfFiles="1" but it allowed to upload more files also...
Reply
Phil Williams January 02, 2014
Brilliant article thank you, though I have a query. I can upload multiple files no
problem, but any additional code (apart from the file save) that I add in
AjaxFileUpload1_UploadComplete does not execute at all. If I put any code before the
file save then the save itself wont work, any code after the save works but additional
code doesn't work I am totally baffled. Any suggestions would be most appreciated.
Reply
Rajiv Yadav February 14, 2014
Hell sir,
How to upload .MDF or ms access database file for save in folder using fileupload control
in asp.net c#?.
Reply
angshu44 April 03, 2014
your post is very useful and your way of demonstration is very helpful and easy to
understand.
but i have one suggestion to you that if you modify this post with a remove
button(including code) in the bottom of uploaded image where user can delete the
uploaded image; that would be more suitable for user....
thank you again...
Reply
Lalit Raghuvanshi April 03, 2014
Thanks angshu44 for your feedback and suggestions...i will update the article
as per your suggestion. so stay connected and keep reading..:)
Anonymous April 20, 2014
but how can i display image after i search it
Reply
deva prasad May 07, 2014
dude nice article.this very much helpful.please keep on posting your articles.helpful to
us
Reply
Lalit Raghuvanshi May 08, 2014
Thanks deva prasad for your feedback..it is always nice to hear that my
articles helped anyone..keep reading and stay connected..
Newer Post Older Post Home
Subscribe to: Post Comments ( Atom )
Enter your comment...
Comment as:
Google Account
Publish
Preview
If you have any question about any post, Feel free to ask.You can simply drop a comment below
post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated.
Also try to leave comments from your account not from the anonymous account so that i can
respond to you easily..
Create a Link
Links to this post
Copyright | Terms of Use & Privacy Policy | Disclaimer
Copyright 2013 Webcodeexpert.com. All Rights Reserved. Powered by blogger
The content is copyrighted to the author Lalit Raghuvanshi and may not be reproduced on other websites without permission.