Upload File With Asp .Net AsyncFileUpload Ajax Control Inside ModalPopupExtender


Asp .Net makes upload file process is easy task. As long as the server upload directory has sufficient permission, we can save file to that directory. Beside that we can specify what kind of file we want to save.

AsyncFileUpload is an Ajax Control to upload file asynchronously. Click on browse/select file button and choose file location then the control will automatically upload the file to server. The file uploading results can be checked both in the server and client sides.

Its basic tag example is <ajaxToolkit:AsyncFileUpload ID=”asyncfileupload1″ runat=”server” OnClientUploadComplete=”uploadcomplete” OnClientUploadError=”uploaderror” />. It have client event OnClientUploadComplete contains client script function that execute when upload file is success and OnClientUploadError is same but execute when upload file is error.
Other client event is OnClientUploadStarted executes when upload process started.
Also it have server event UploadedComplete and UploadedFileError that execute on server when upload file is success and error respectively.
For complete description explanation about AsyncFileUpload please refer to link http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/AsyncFileUpload/AsyncFileUpload.aspx

In this post, I will write example of AsyncFileUpload Ajax Control along with ModalPopup Extender as container. I already have example of using ModalPopupExtender Ajax Control at this link Create a PopUp Dialog with ModalPopupExtender AjaxControlToolkit
This example will only allow image (jpg, gif, png) file to be uploaded.

AsyncFileUpload Basic

Design Mode source code:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<!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 runat="server">
    <title></title>
    <script type="text/javascript">
        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);
        }

        function uploadError(sender, args) {
            addToClientTable(args.get_fileName(), "<span style='color:red;'>" + args.get_errorMessage() + "</span>");
        }
        function uploadComplete(sender, args) {
            var contentType = args.get_contentType();
            var text = args.get_length() + " bytes";
            if (contentType.length > 0) {
                text += ", '" + contentType + "'";
            }
            addToClientTable(args.get_fileName(), text);
        }

        function uploadStart(sender, args) {
            var filename = args.get_fileName();
            var filext = filename.substring(filename.lastIndexOf(".") + 1);
            if (filext == "jpg" || filext == "gif" || filext == "png") {
                return true;
            }
            else {
                //you cannot cancel the upload using set_cancel(true)
                //cause an error
                //will  automatically trigger event OnClientUploadError
                var err = new Error();
                err.name = 'My API Input Error';
                err.message = 'Only .jpg, .gif, .png files';
                throw (err);


                return false;
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" EnablePartialRendering="true">
        </asp:ToolkitScriptManager>
        <asp:AsyncFileUpload ID="AsyncFileUpload1" runat="server" OnClientUploadStarted="uploadStart" OnClientUploadComplete="uploadComplete"
         OnClientUploadError="uploadError" />
        <asp:Table id="clientSide" runat="server" ></asp:Table>
    </div>
    </form>
</body>
</html>

Basic rule to use Ajax Control Toolkit is adding reference to AjaxControlToolkit.dll and register the assembly on page. ToolkitScriptManager tag must be included to enable Ajax control toolkit.

The AsyncFileUpload has uploadStart() client function that will executed when upload is started. This function checks file extension. If it is not image then raise an error to cancel upload process.

You can check a thread of raising an error to cancel upload at this link http://forums.asp.net/t/1553921.aspx/1

uploadComplete() is used to insert table rows containing success upload information. uploadError() is executed when upload process has error.

Code behind file source code:

Imports System.IO
Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub AsyncFileUpload1_UploadedComplete(ByVal sender As Object, ByVal e As AjaxControlToolkit.AsyncFileUploadEventArgs) Handles AsyncFileUpload1.UploadedComplete
        Dim savepath As String
        savepath = Server.MapPath("~/Uploads/" & Path.GetFileName(e.filename))
        AsyncFileUpload1.SaveAs(savepath)

    End Sub
End Class

Here I only write UploadedComplete to save uploaded file to destination folder. AsyncFileUploadEventArgs can be used to retrieve filename and filesize.

AsyncFileUpload in ModalPopupExtender

Design Mode source code:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="AsyncUploadModal.aspx.vb" Inherits="AsyncUploadModal" %>
<%@ 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 runat="server">
    <title></title>
    <style type="text/css">
    .modalbackground 
    {
        background-color:Gray;
        opacity: 0.5;
        filter:Alpha(opacity=50);
    }
    
    .modalpopup 
    {
        background-color:White;
        padding:6px 6px 6px 6px;
    }
    </style>
    <script type="text/javascript"> 
       
        var fileuploaded;
        function uploadcomplete(sender, args) {
            fileuploaded = args.get_fileName();          
            $get("img1").style.display = "block";
            $get('img1').src = "Uploads/" + fileuploaded;
			
			 //clear input text
            var fileInputElement = sender.get_inputFile();
            fileInputElement.value = "";
			
            $get('asyncupload').style.display = "none";
          
        }

        function uploadStart(sender, args) {
            var filename = args.get_fileName();
            var filext = filename.substring(filename.lastIndexOf(".") + 1);
            if (filext == "jpg" || filext == "gif" || filext == "png") {
                return true;
            }
            else {
                //you cannot cancel the upload using set_cancel(true)
                //cause an error
                //will  automatically trigger event OnClientUploadError
                var err = new Error();
                err.name = 'My API Input Error';
                err.message = 'Only .jpg,.gif,.png  files';
                throw (err);


                return false;
            }
        }

        function uploaderror(sender, args) {
            alert(args.get_errorMessage());
        }

        function _ok() {
           window.location.reload();
        }

        function _cancel() {
			if (fileuploaded!="") {
            PageMethods.cancelupload('<%= Server.Mappath("~/Uploads").Replace("\","/") %>' + '/' + fileuploaded);
			}
        }

       

    </script>
</head>
<body >
    <form id="form1" runat="server">
    <div>
     <ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" EnablePartialRendering="true" EnablePageMethods="true">
        </ajaxToolkit:ToolkitScriptManager>
     
        <asp:Table ID="Table1" runat="server">
        <asp:TableHeaderRow BackColor="BlueViolet">
            <asp:TableHeaderCell ForeColor="White">
                Img
            </asp:TableHeaderCell>
            <asp:TableHeaderCell ForeColor="White">
                File Name
            </asp:TableHeaderCell>
        </asp:TableHeaderRow>
        
        </asp:Table>  
        <br />
       
       <asp:Button ID="btnadd" runat="server" Text="Add Image" />
        <asp:Panel ID="panel1" runat="server" BorderStyle="Solid" BorderWidth="1px" BorderColor="WhiteSmoke" CssClass="modalpopup">
            <asp:Panel ID="panel2" runat="server"  Style="cursor: move;background-color:#DDDDDD;border:solid 1px Gray;color:Black">
            <div>
                Upload a File
            </div>
            </asp:Panel>
           <ajaxToolkit:AsyncFileUpload ID="asyncupload" runat="server" OnClientUploadComplete="uploadcomplete" 
			OnClientUploadError="uploaderror" OnClientUploadStarted="uploadStart"/><br />
            <img id="img1" style="width:300px;height:300px;display:none" /> <br />
            <asp:Button ID="btnok" runat="server" Text="OK" />
            <asp:Button ID="btncancel" runat="server" Text="Cancel" />
        </asp:Panel>

        <ajaxToolkit:ModalPopupExtender id="modalpopup" runat="server" Drag="true" BackgroundCssClass="modalbackground" Y="100" X="250"
           TargetControlID="btnadd" PopupControlID="panel1" PopupDragHandleControlID="panel2"
         OkControlID="btnok" OnOkScript="_ok()" CancelControlID="btncancel" OnCancelScript="_cancel()" ></ajaxToolkit:ModalPopupExtender>
         
    </div>
    </form>
</body>
</html>

ToolkitScriptManager is a must if we use Ajax Control. I have Asp .Net Table control to show list of image file on upload folder. Using table control is for sake of simplicity. Add Image button acts as a TargetControlID of ModalPopup.
So when you click that button then the popup panel will show along with AsyncFileUpload inside it.

I have uploadStart() client script function to check file extension. If the extension is not image then the method raises error to cancel upload.

uploadcomplete() client script method has code to clear asyncfileupload text value

ModalPopup has Ok and Cancel button. If OK button is clicked then OnOkScript _ok() will reload page to refresh list of images inside Uploads folder. On the other hand, if for any reason user want to cancel uploaded file then I have to delete that file at _cancel() method.
This _cancel() has been specified at ModalPopup’s OnCancelScript. Inside this _cancel() method I have PageMethods.cancelupload(). This PageMethods is used to call server side function which in this example is cancelupload(). cancelupload() is written in code behind file. Also I have to write EnablePageMethods="true" attribute inside ToolkitScriptManager to enable the PageMethods in client script.

Code behind file source code:

Imports AjaxControlToolkit
Imports System.IO
Imports System.Web.Services
Partial Class AsyncUploadModal
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        ReloadList()
    End Sub

    Protected Sub uploadedcomplete(ByVal sender As Object, ByVal e As AjaxControlToolkit.AsyncFileUploadEventArgs) Handles asyncupload.UploadedComplete
        Dim savepath As String
        Dim filename As String = e.filename
        Dim fileext As String = Path.GetExtension(filename).ToLower()
        If fileext = ".jpg" Or fileext = ".gif" Or fileext = ".png" Then
            savepath = Server.MapPath("~/Uploads/" & Path.GetFileName(e.filename))
            asyncupload.SaveAs(savepath)
        End If
        

    End Sub

    Protected Sub uploadedfileerror(ByVal sender As Object, ByVal e As AjaxControlToolkit.AsyncFileUploadEventArgs) Handles asyncupload.UploadedFileError

    End Sub

    Protected Sub ReloadList()
        Dim directory As New DirectoryInfo(Server.MapPath("~/Uploads"))
        Dim arrfile As FileInfo()
        arrfile = directory.GetFiles()
        For Each f As FileInfo In arrfile
            If f.Extension.ToLower() = ".jpg" Or f.Extension.ToLower() = ".gif" Or f.Extension.ToLower() = ".png" Then
                Dim tr As New TableRow()

                Dim tc As New TableCell()
                tc.Text = "<img src='uploads/" & f.Name & "' style='width:120px;height:100px' />"
                tr.Cells.Add(tc)

                tc = New TableCell()
                tc.Text = f.Name
                tr.Cells.Add(tc)

                Table1.Rows.Add(tr)
            End If
           
        Next
    End Sub

    <WebMethod()> _
    Public Shared Sub cancelupload(ByVal filepath As String)
        File.Delete(filepath)
    End Sub
End Class

Inside uploadedcomplete() function there is SaveAs() method to save chosen file to destination folder. Also I can check the file extension with AsyncFileUploadEventArgs.

ReloadList() function lists image files in Uploads directory and write it to Table Server Control.

cancelupload delete uploaded file if user clicks ModalPopup Cancel button. This method has WebMethod() attribute indicating that it can be executed via client script.

Snapshots of this web application:

  1. Page Load will show list of image in Uploads directory
  2. Add image button is clicked and then ModalPopup with AsyncFileUpload inside it are shown
  3. If upload image is complete then the image will be shown need to be confirmed by user and AsyncFileUpload visibility set to hidden.
  4. ModalPopup OK button is clicked, so the list will refresed and uploaded file is shown

Regards,
Agung Gugiaji

About these ads

5 responses to “Upload File With Asp .Net AsyncFileUpload Ajax Control Inside ModalPopupExtender

  1. Thanks sir, it helps me lot..
    Nice

  2. I got this web site from my buddy who informed me on the
    topic of this web page and at the moment this
    time I am browsing this site and reading very informative articles
    or reviews at this place.

  3. * gugiaji. (I read wrong. Thanks to gugiaji )

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s