AsyncFileUpload Example In Asp.Net For Asynchronous Uploads

This example illustrate how to use Ajax AsycFileUpload Control In Asp.Net to upload files asynchronously with use of AjaxControlToolkit OnClientUploadComplete, OnUploadedComplete and OnClientUploadError events.

Download Latest AjaxControlToolkit and put it in Bin folder of your application. register it in html source of page using Register Assembly page directive at the top of page.

Drag and place ToolkitScriptManager, AsyncFileUpload Control  and one label from toolbox on page.label will be used to display success or failure message based on OnClientUploadComplete and OnClientUploadError event raised.

We also need to reset default file size limit of 4mb to enable large file uploads.

AsyncFileUpload example in asp.net ajax

HTML SOURCE OF PAGE
Register Toolkit
   1:  <%@ Page Language="C#" AutoEventWireup="true"  
   2:           CodeFile="Default.aspx.cs" Inherits="_Default" %>
   3:  <%@ Register Assembly="AjaxControlToolkit" 
   4:               Namespace="AjaxControlToolkit" 
   5:               TagPrefix="ajax" %>
   1:  <head runat="server">
   2:      <title></title>
   3:  <script type = "text/javascript">
   4:  function Success() 
   5:  {
   6:  document.getElementById("lblMessage").innerHTML = "File Uploaded";
   7:  }
   8:   
   9:  function Error() 
  10:  {
  11:  document.getElementById("lblMessage").innerHTML = "Upload failed.";
  12:  }
  13:  </script>
  14:  </head>
  15:  <body>
  16:  <form id="form1" runat="server">
  17:  <div>
  18:  <ajax:ToolkitScriptManager ID="ToolkitScriptManager1" 
  19:                             runat="server"/>
  20:   
  21:  <ajax:AsyncFileUpload ID="AsyncFileUpload1" runat="server" 
  22:                        OnUploadedComplete="SaveUploadedFile" 
  23:                        OnClientUploadComplete="Success" 
  24:                        UploaderStyle="Modern" 
  25:                        OnClientUploadError="Error" 
  26:                        ThrobberID="loader"/>
  27:  <asp:Image ID="loader" runat="server" 
  28:             ImageUrl ="~/Loader.gif"/>
  29:   <asp:Label ID="lblMessage" runat="server" Text=""/>
  30:  </form>
  31:  </body>

C# CODE
protected void SaveUploadedFile(object sender, EventArgs e)
    {
        string uploadedFileName = Path.GetFileName(AsyncFileUpload1.FileName);
        AsyncFileUpload1.SaveAs(Server.MapPath("~/") + uploadedFileName);
    }

VB.NET
Protected Sub SaveUploadedFile(sender As Object, e As EventArgs)
 Dim uploadedFileName As String = Path.GetFileName(AsyncFileUpload1.FileName)
 AsyncFileUpload1.SaveAs(Server.MapPath("~/") & uploadedFileName)
End Sub


Download Sample Code


If you like this post than join us or share

1 comments:

Anonymous said...

How can we check file is already exists on physical location,


Find More Articles