• Using AsyncFileUpload Control in ASP.NET AJAX

    Posted on October 25, 2012 by in ASP.NET, C#, Dotnet

    Finally, it has become possible to easily add AJAX file uploading capabilities to ASP.NET applications. The newly released version of the AJAX Control Toolkit ships with two new controls, one of them is called AsyncFileUpload control. AsyncFileUpload is an ASP.NET AJAX Control that allows you asynchronously upload files to server. The file uploading results can be checked both in the server and client sides. Using AsyncFileUpload Control in ASP.NET AJAX is simple.

    Firstly, Add a ScriptManager to your page if have not already.The AsyncFileUpload control is initialized with this code.

    <ajaxToolkit:AsyncFileUpload ID="AsyncFileUpload1" OnClientUploadError="uploadError"
         OnClientUploadComplete="uploadComplete" runat="server"
         Width="400px" UploaderStyle="Modern" OnUploadedComplete = "AsyncFileUpload1_UploadedComplete" 
         UploadingBackColor="#CCFFFF"/>
        
        <span id="spnUploadStatus"></span>
    

    C# to upload the file.

    protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
    {
      if (AsyncFileUpload1.HasFile)
      {
        string strPath = MapPath("~/Uploads/") + Path.GetFileName(e.FileName);
        AsyncFileUpload1.SaveAs(strPath);
      }
    }
    

    Sample Javascript Code for complete an error Events.

           function uploadError(sender, args) {
                document.getElementById('spnUploadStatus').innerHTML = args.get_errorMessage();
            }
            function uploadComplete(sender, args) {
                document.getElementById('spnUploadStatus').innerHTML = args.get_fileName();
            }
    

    For more events and properties please visit the ajax control tool kit website here

    Working Example

    We will see the example to upload a file while fulfilling the requirements

    1. The File Upload should be done asynchronously.
    2. User should be restricted to upload only files with certain extensions.
    3. The name of the file should be prefixed with a random string, so that uploaded file should not replace the existing file
    4. Return the new file name to front end for further processing.
    5. The AsyncFileUpload control has OnClientUploadStarted event where you can check for file extensions and restrict if necessary. If you would like stop from uploading to server, you can just throw to javascript error which would fire OnClientUploadError and stop the upload. Here is sample Code

              function uploadStart(sender, args) {
                  var fileName = args.get_fileName();
                  var fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
      
                  if (fileExt == "xls" || fileExt == "xlsx") {
                      return true;
                  } else {
                      //To cancel the upload, throw an error, it will fire OnClientUploadError 
                      var err = new Error();
                      err.name = "Upload Error";
                      err.message = "Please upload only Excel files (.xls,.xlsx)";
                      throw (err);
      
                      return false;
                  }
              }
      

      In the AsyncFileUpload1_UploadedComplete above is changed the filename by a adding randomstring or guid to make the filename unique. You cannot directly assign it to server side field.

          protected void AsyncFileUpload1_UploadedComplete(object sender, AsyncFileUploadEventArgs e)
          {
              string importPath = MapPath("~/docs/imports/"); 
              //prepend the filename with a guidstring so that it is unique
              string fileName = System.Guid.NewGuid().ToString() + Path.GetFileName(e.FileName);
              hdnFileName.Value = fileName;
      
              AsyncFileUpload1.SaveAs(importPath + filename);
          }
      

      The above code does not work, ie the new file name is not set to hdnFileName field. That is because AsyncFileUpload control uses an iframe to post it files to server. This means, nothing on the page is posted back when uploading the file. But it is easy fix,

      Csharp Code

                  ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "newfile"
                      , "window.parent.$find('" + AsyncFileUpload1.ClientID + "').newFileName='" + filename + "';", true);
      

      Javascript Code to retrieve the new file name

             document.getElementById('spnUploadStatus').innerHTML = "New File Name : " + sender.newFileName;
      

      Please find Complete Code below

      ASPX CODE

      <%@ Page Language="C#" AutoEventWireup="true"   CodeFile="AsyncFileUpload.aspx.cs"  Inherits="AsyncFileUpload_AsyncFileUpload" %>
      <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit"  TagPrefix="ajaxToolkit" %>
      
      <!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>
          <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
          <script type="text/javascript">
      		$(document).ready(function () {
      		    //Excel Import Click,If the donot like the style of the control you can put an image of your choice
      			//on the Image click, call the AsyncFileUpload1 control click as below
                  $("#imgExcelImport").click(function () {
                      $("#<%=AsyncFileUpload1.ClientID%>_ctl02").click();
                  });
      		});
      	
              function uploadStart(sender, args) {
                  var fileName = args.get_fileName();
                  var fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
      
                  if (fileExt == "xls" || fileExt == "xlsx") {
                      return true;
                  } else {
                      //To cancel the upload, throw an error, it will fire OnClientUploadError 
                      var err = new Error();
                      err.name = "Upload Error";
                      err.message = "Please upload only Excel files (.xls,.xlsx)";
                      throw (err);
      
                      return false;
                  }
              }
      
              function uploadComplete(sender, args) {
                  var fileName = sender.newFileName;
                  updateUploadStatus("success", "File Uploaded Successfully...Reading File Contents")
                  ReadFileContents(fileName);
              }
              function uploadError(sender, args) {
                  var errmsg = args.get_errorMessage();
                  updateUploadStatus("error", "There was Error Uploading the file. Error :" + errmsg);
              }
      
              function updateUploadStatus(status, message) {
                  var uploadstatlbl = $("span[id$='lblUploadStatus']");
                  uploadstatlbl.html(message);
                  if (status == "error") {
                      uploadstatlbl.removeClass("spansuccess").addClass("spanerror");
                  } else {
                      uploadstatlbl.removeClass("spanerror").addClass("spansuccess");
                  }
              }
      
              function ReadFileContents(fileName) {
                  //READ the Contents of the file not part of this tutorial
              }        
          </script>
          <ajaxToolkit:ToolkitScriptManager runat="Server" EnablePartialRendering="true" ID="ScriptManager1" />
      </head>
      <body>	
                          <div id="divAjaxUpload" style="display:none;">
                              <ajaxToolkit:AsyncFileUpload
                                  OnClientUploadStarted="uploadStart" OnClientUploadError="uploadError" OnClientUploadComplete="uploadComplete" onuploadedcomplete="AsyncFileUpload1_UploadedComplete" 
                                  runat="server" ID="AsyncFileUpload1" Width="400px" UploaderStyle="Modern" 
                                  UploadingBackColor="#CCFFFF"/>&nbsp;
                          </div>
      <div id="content">
        <asp:Label ID="lblUploadStatus" runat="server" CssClass="spansuccess"></asp:Label>
        
                              <div class="featurescontainer">
                                       <a href="javascript:void(0)" title="Excel Import">
                                          <img src="images/ExcelImport.gif" class="excelimport" id="imgExcelImport" />
                                       </a>
                              </div>  
      </div>				
      </body>
      </html>
      

      Code Behind

      using System;
      using System.Collections.Generic;
      using System.Web;
      using System.Web.UI;
      using System.Web.UI.WebControls;
      using System.IO;
      using AjaxControlToolkit;
      
      public partial class BudgetBatch : System.Web.UI.Page
      {
          protected void Page_Load(object sender, EventArgs e)
          {
              //string importPath = Request.PhysicalApplicationPath;
      
          }
          protected void AsyncFileUpload1_UploadedComplete(object sender, AsyncFileUploadEventArgs e)
          {
              try
              {
                  string importPath = MapPath("~/docs/imports/");
                  string filename = Helper.generateRandomString() + Path.GetFileName(e.FileName);
                  
                  //pass filename to front end;
                  ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "newfile"
                      , "window.parent.$find('" + AsyncFileUpload1.ClientID + "').newFileName='" + filename + "';", true);
      
                  AsyncFileUpload1.SaveAs(importPath + filename);
              }
              catch (Exception ex)
              {
                  ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "size", "top.$get(\"" + lblUploadStatus.ClientID + "\").innerHTML = 'There was an Error Processing the Request : Error " + ex.Message.ToString()  + "';", true);
              }
          }
          protected void AsyncFileUpload1_UploadedFileError(object sender, AsyncFileUploadEventArgs e)
          {
              ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "size", "top.$get(\"" + lblUploadStatus.ClientID + "\").innerHTML = 'There was an Error Processing the Request : Error " + e.StatusMessage + "';", true);
          }
      }
      

      The file select dialog directly opens when the Excel Import image to the right corner is clicked.

      asyncFileUpload

      Be Sociable, Share!
        Post Tagged with

    Leave a Reply