Wednesday, 6 November 2013

Ajax AsyncFileUpload control example in asp.net to upload files to server using C#/VB.NET

Hi friends,in this article I will explain about Ajax AsyncFileUpload control example in asp.net to upload files to server using C#/VB.NET.
I already explained in the previous articles about CSS - Gmail-style progress bar when page is loading,Marquee tag or How to Scroll Text From left to right or How to Move the Text in HTML,C#/VB.NET:Save the generated pdf directly to the server directory folder without user prompt in ASP.NET and JQuery:How to Display Current Date and Time on Webpage using ASP.NET


In ASP.NET:
<%@Register  Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax"%>
<html xmlns="http://www.w3.org/1999/xhtml" > 
<head id="Head1" runat="server"> 
    <title>Ajax AsyncFileUpload - How to use AsyncFileUpload in asp.net ajax</title> 
    <script type="text/javascript">
        function showConfirmation() {
            document.getElementById('lblStatus').innerText = 'Image Uploaded Successfully.';
        }
        function uploadError(sender, args) {
            document.getElementById('<%=lblStatus.ClientID %>').innerText = args.get_fileName(), "<span style='color:red;'>" + args.get_errorMessage() + "</span>";
        }
        function StartUpload(sender, args) {
            document.getElementById('<%=lblStatus.ClientID %>').innerText = 'Uploading Started.';
        }
</script> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div> 
        <asp:ScriptManager  ID="ScriptManager1" runat="server" > 
        </asp:ScriptManager> 
           <asp:Image runat="server" ID="imgphoto" ImageUrl="~/Images/empty_img.jpg"  />
        <ajax:AsyncFileUpload ID="imgUpload" runat="server"
             
                OnClientUploadError="uploadError"
                OnUploadedComplete="UploadComplete"                 
                CompleteBackColor="Lime" UploaderStyle="Modern"
                ErrorBackColor="Red" ThrobberID="Throbber" UploadingBackColor="#66CCFF" Width="250px" />
    
        <br />             
         <asp:Label ID="Throbber" runat="server" Style="display: none">
         <img src="Images/loading-gif-animation.gif" align="absmiddle" width="30" height="30" alt="loading" /> </asp:Label>
        <asp:Label  ID="lblStatus" runat="server" Font-Size="Large" ></asp:Label>  
        <asp:Label ID="lbl" runat="server"></asp:Label>         
    </div> 
    </form> 
</body> 
</html> 


In C#.NET
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class AjaxFileUpload : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }
      protected void UploadComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e) 
    {
    
        if (imgUpload.HasFile)
        {
            System.Threading.Thread.Sleep(1000);
            string filePath = Request.PhysicalApplicationPath + "Images\\" + imgUpload.PostedFile.FileName;
            if (System.IO.File.Exists(filePath))
            {              
              
                Response.Write("<script>alert('exists');</script>");
                lbl.Text = "File Already Exists,Select another File";
                return;
            }
            else
            {
            imgUpload.SaveAs(filePath);
                lblStatus.Text = "Image Uploaded Successfully.";
            }
        }
        else
        {
            lblStatus.Text = "Please Upload The Image";
        }
    }  
}

In VB.NET:
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

Partial Public Class AjaxFileUpload
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

    End Sub
    Protected Sub UploadComplete(ByVal sender As Object, ByVal e As AjaxControlToolkit.AsyncFileUploadEventArgs)

        If imgUpload.HasFile Then
            System.Threading.Thread.Sleep(1000)
            Dim filePath As String = (Request.PhysicalApplicationPath & "Images\") + imgUpload.PostedFile.FileName
            If System.IO.File.Exists(filePath) Then

                Response.Write("<script>alert('exists');</script>")
                lbl.Text = "File Already Exists,Select another File"
                Return
            Else
                imgUpload.SaveAs(filePath)
                lblStatus.Text = "Image Uploaded Successfully."
            End If
        Else
            lblStatus.Text = "Please Upload The Image"
        End If
    End Sub
End Class



The output of the above code as shown in the below figure.

When we select the image it shows the path as c:\Fakepath

To overcome c:\Fakepath add the below code in StartUpload() and UploadComplete() functions.
var ctrlText = sender.get_element().getElementsByTagName("input");
            for (var i = 0; i < ctrlText.length; i++) {
                if (ctrlText[i].type == "text") {
                    ctrlText[i].value = args.get_fileName();
                    //ctrlText[i].style.backgroundColor = "white";
                }
            }

If you like my blog or articles, you can appreciate by leaving your comments or Liking my Facebook pageAspdotnet-kishore, following on Google+ Aspdotnet-Kishore, Twitter  on AspdotnetKishore, Linked in Aspdotnet-Kishore, stumbling my posts on stumble upon and subscribing on  RSSfeed Aspdotnet-Kishore for free updates directly to your Email inbox . Watch my blog  for more articles."

No comments:

Post a Comment

© 2012-2018 Aspdotnet-Kishore.blogspot.com. All Rights Reserved.
The content is copyrighted to Kishore and may not be reproduced on other websites without permission from the owner.