File Upload control using Ajax and javascript in asp.net

How to Make File upload using Ajax control in asp.net

Javascript file
  <script type="text/javascript" language="javascript">

function uploadError(sender,args)
{
document.getElementById('lblStatus').innerText = args.get_fileName(),
"<span style='color:red;'>" + args.get_errorMessage() + "</span>";
addToClientTable(args.get_fileName(), "<span style='color:red;'>" + args.get_errorMessage() + "</span>");

}

function StartUpload(sender,args)
{
document.getElementById('lblStatus').innerText = 'Uploading Started.';
}

function UploadComplete(sender,args)
{
var filename = args.get_fileName();
var contentType = args.get_contentType();
var text = "Size of " + filename + " is " + args.get_length() + " bytes";
if (contentType.length > 0)
{
text += " and content type is '" + contentType + "'.";
}
document.getElementById('lblfilename').innerText = filename;
document.getElementById('lblStatus').innerText = text;
addToClientTable(args.get_fileName(), text);
}

function fillCell(row, cellNumber, text) {
var cell = row.insertCell(cellNumber);
cell.innerHTML = text;
cell.style.borderBottom = cell.style.borderRight = "solid 1px #aaaaff";
}
function addToClientTable(name, text) {
var table = document.getElementById("<%= clientSide.ClientID %>");
var row = table.insertRow(0);
fillCell(row, 0, name);
fillCell(row, 1, text);
}

</script>


Design page

<asp:ScriptManager ID="scman" runat="server">
</asp:ScriptManager>

  <asp:UpdatePanel ID="update1" runat="server">
<ContentTemplate>
<AjaxToolkit:AsyncFileUpload ID="AsyncFileUpload1" Width="400px" runat="server" OnClientUploadError="uploadError"
OnClientUploadStarted="StartUpload" OnClientUploadComplete="UploadComplete" CompleteBackColor="Lime"
UploaderStyle="Modern" ErrorBackColor="Red" ThrobberID="Throbber" OnUploadedComplete="AsyncFileUpload1_UploadedComplete"
UploadingBackColor="#66CCFF" />
<br />
<asp:Label ID="Throbber" runat="server" Style="display: none" Font-Bold="true">
<img src="images/indicator-new.gif" align="absmiddle" alt="loading" />
</asp:Label>
<asp:Label ID="lblfilename" runat="server" Style="font-family: Arial; color:Green; font-size: small;"></asp:Label>
<br />
<asp:Label ID="lblStatus" runat="server" Style="font-family: Arial; font-size: small;"></asp:Label>
<table style="border-collapse: collapse; border-left: solid 1px #aaaaff; border-top: solid 1px #aaaaff;"
runat="server" cellpadding="3" id="clientSide" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="AsyncFileUpload1" EventName="UploadedComplete" />
</Triggers>
</asp:UpdatePanel>

And Code behind page for file upload

 protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
System.Threading.Thread.Sleep(1000);
if (AsyncFileUpload1.HasFile)
{
string strPath = MapPath("~/Uploads/") + System.IO.Path.GetFileName(e.filename);
AsyncFileUpload1.SaveAs(strPath);
}
}

Ebook Download
View all
Learn
View all