Image Uploader using AjaxFileUpload and ModalPopup in ASP.NET

Hi Guys,

This time I made a image uploader using AjaxFileUpload and ModalPopup in ASP.NET, but I added the functionality of viewing the thumbnails of the uploading images which was not available in AjaxFileUpload. And when you click on delete button of the uploading images the thumbnail also gets removed. I did some styling to make the image uploader look good. Hope you like it. 


Before you Start,

1) Any version of Visual Studio 

Step One : The Solution

First create a WebSite as following.



Step Two : Code and Styles

Open the Styles.css and paste the following css,

.Modal {
-webkit-box-shadow: rgba(0,0,0,.2) 0 4px 16px;
box-shadow: rgba(0,0,0,.2) 0 4px 16px;
-webkit-user-select: none;
background: #fff;
border: 1px solid #acacac;
color: #000;
position: absolute;
z-index: 2101;
outline: none;
height:auto;
font-family: arial,sans-serif;
font-size:small;
}


.Header {
-webkit-user-select: none;
background: #fff;
color: #000;
font-size: 20px;
padding: 6px 8px 15px;
position: relative;
vertical-align: middle;
border-top: #fff 10px solid;
border-left: #fff 10px solid;
border-right: #fff 10px solid;
background-color: #f5f5f5;
border-color: #f5f5f5 ;
border: #f5f5f5 10px solid;
font-family: arial,sans-serif;
font-size:small;
}

.CloseButton
{
    padding-left:100px;
float:right;
top:5%;
height:16px;
width:16px;
}

div {
display: block;
}

/* Ajax File Upload */

.ajax__fileupload {
    padding: 4px;
    border: #D3D3D3 1px solid;
    overflow: auto;
    font-family: arial,sans-serif !important;
    font-size:small !important;
}

.ajax__fileupload_selectFileContainer {
    height: 24px;
    line-height: 24px;
}

.ajax__fileupload_selectFileButton {
    display:block;
    height: 24px;
    line-height: 24px;
    width: 100px !important;
    text-align: center;
   
    color: grey !important;
    cursor: pointer;
    margin-right: 4px;
    font-size: 12px !important;
    font-weight: bold !important;
     background-color: white !important; 
     background-image:url('./Images/Select.png') !important;
    background-repeat:no-repeat !important;
    background-position:left !important;
}

.ajax__fileupload_selectFileButton:hover {
    background-color: #000000;
    color: #ffffff;
}

.ajax__fileupload_topFileStatus {
    color: rgb(127, 126, 126);
}

.ajax__fileupload_ProgressBarHolder 
{
    margin-right: 70px;
    _margin-right: 0;
}

.ajax__fileupload_uploadbutton {
    width: 100px !important;
    text-align: center;
    cursor: pointer;
   
    font-weight: bold;
     background-color: white !important;
    color: Grey !important;
    background-image:url('./Images/Upload.png') !important;
    background-repeat:no-repeat !important;
    background-position:left !important;
}

.ajax_fileupload_cancelbutton {
    width: 60px;
    text-align: center;
    cursor: pointer;
    color: white;
    font-weight: bold;
    background-color: white !important;
}

.ajax__fileupload_dropzone {
    border-style: dotted; 
    border-width: 1px; 
    line-height: 50px; 
    text-align:center;
    _text-align:left; /* IE Only */
    margin-bottom:2px;
}

.ajax__fileupload_queueContainer 
{
    border: #A9A9A9 1px solid;
    border-width: 1px; 
    margin-top:2px; 
    padding:4px;
    clear: both;
}

.ajax__fileupload_progressBar {
    padding-left:4px; 
    background-color: white !important; 
     background-image:url('./Images/Progress.gif') !important;
    background-repeat:no-repeat !important;
    background-position:left !important;
}

.ajax__fileupload_footer {
    margin-top: 2px;
    line-height: 20px;
    height: 20px;
}

.ajax__fileupload_fileItemInfo {
    line-height: 20px;
    height: 20px;
    margin-bottom: 2px;
    overflow: hidden;
   color: rgb(127, 126, 126) !important
}

.ajax__fileupload_fileItemInfo .filename {
    font-weight: bold;
}

.ajax__fileupload_fileItemInfo .uploadstatus {
    font-style: italic;
}

.ajax__fileupload_fileItemInfo .removeButton {
    cursor: pointer;
    background-color: white !important;
    color: white !important;
    width: 100px !important;
    height: 20px;
    line-height: 20px;
    text-align: center ;
    display: block;
    float: right !important;
    background-image:url('./Images/Trash.png') !important;
    background-repeat:no-repeat !important;
    background-position:left !important;
    
}

.ajax__fileupload_fileItemInfo .uploadedState {
    color: rgb(127, 126, 126) !important;
    background-color: #fff;
}

.ajax__fileupload_fileItemInfo .uploadingState {
    color: rgb(127, 126, 126) !important;

    background-color: #fff;
}

.ajax__fileupload_fileItemInfo .pendingState {
    color:rgb(127, 126, 126) !important;
    background-color: #fff;
}

.ajax__fileupload_fileItemInfo .errorState {
    color: #ffffff;
    background-color: #ff0000;
}

.ajax__fileupload_fileItemInfo .cancelledState {
    color: #900;
    background-color: #fff;
}

/*Check*/
.ajax__fileupload_selectFileContainer {
display: inline-block;
    overflow: hidden;
    position: relative;
    width: 80px;
    /*float: left;*/
}

.ajax__fileupload_selectFileContainer input {
    border: medium none;
    cursor: pointer;
    height: 40px;
    margin: 0;
    opacity: 0;
    position: absolute;
    right: 0;
    top: 0;
}

.ajax__fileupload_fileItemInfo 
{
    position: relative;
    z-index: 0;
}

.ajax__fileupload_fileItemInfo div.removeButton 
{
    position: absolute;
    top: 0;
    right: 0;
}

.imgSpan {
     width : 100px;
     height : 100px;
}

.alert-success {
  color: #3c763d;
  background-color: #dff0d8;
  border-color: #d6e9c6;
}
.alert-success hr {
  border-top-color: #c9e2b3;
}
.alert-success .alert-link {
  color: #2b542c;
}

.Img {
}

Then Open the Default.aspx and paste the following HTML.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

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



<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="Styles.css" rel="stylesheet" />
    
    <script src="Scripts/jquery-1.11.1.min.js"></script>
    <script type="text/javascript">
        var fileIndex = 0;

        $(document).ready(function () {
            $('#myAjaxUploader_Html5InputFile').bind("change", handleFileSelect);
            
            $('.ajax__fileupload_queueContainer').bind("click", function (e) { e = e || window.event;
                var target = e.target || e.srcElement;
                var arr = target.id.split('_',4);
                var indArr;

                var divs = document.getElementsByClassName("ajax__fileupload_fileItemInfo");
                var imgs = document.getElementsByTagName("Img");
                var index = 0;
                indArr = new Array(divs.length);

                for (var j = 0; j < imgs.length; j++) {

                for (var i = 0; i < divs.length; i++) {
                    var marr;
                   
                    if (i == 0)
                        marr = divs[i].id.split('_', 4);
                    else {
                        if (i + i >= divs.length)
                            break;
                        marr = divs[i + i].id.split('_', 4);

                    }

                    var mainSpan = document.getElementById('myAjaxUploader_FileItemInfo_' + marr[2]);

                   
                        
                       
                        if (mainSpan.getElementsByTagName('span')[0].innerHTML == imgs[j].id)
                        {
                            indArr[index++] = j;
                        }
                           

                   

                    }
                }


                for (var i = 0; i < imgs.length; i++) {
                   
                    if (indArr.indexOf(i) < 0) {

                        var span;
                        var image_x = imgs[i];
                        if (image_x != null) {
                            span = image_x.parentNode;
                            span.parentNode.removeChild(span);
                            fileIndex--;
                        }
                    }                   

                }          

            });
            

           
            // Setup the dnd listeners.
            var dropZone = document.getElementById('myAjaxUploader_Html5DropZone');
            dropZone.addEventListener('dragover', handleDragOver, false);
            dropZone.addEventListener('drop', handleFileDrop, false);

        });

        function handleDragOver(evt) {
            evt.stopPropagation();
            evt.preventDefault();
            evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
        }


        function handleFileSelect(evt) {
            var files = evt.target.files; // FileList object

            // Loop through the FileList and render image files as thumbnails.
            for (var i = 0, f; f = files[i]; i++) {

                // Only process image files.
                if (!f.type.match('image.*')) {
                    continue;
                }

                var reader = new FileReader();

                // Closure to capture the file information.
                reader.onload = (function (theFile) {
                    return function (e) {
                        // Render thumbnail.
                        var span = document.createElement('span');

                        

                        span.innerHTML = [' <img id=' + escape(theFile.name) +
                            ' class="Img" height="100px" width="100px" style="padding:5px;border : 1px solid grey;" src="', e.target.result,
                                          '" title="', escape(theFile.name), '"/>'].join('');
                       
                        document.getElementById('list').insertBefore(span, null);
                    };
                })(f);

                // Read in the image file as a data URL.
                reader.readAsDataURL(f);
            }

           
        }

       

        function getImageName(n) {
            var divs = document.getElementsByClassName("ajax__fileupload_fileItemInfo");

            

            var arr;
            if (n == 0)
                arr = divs[n].id.split('_', 4);                
            else {              
                  arr = divs[n + n].id.split('_', 4);
                
            }
            
            var mainSpan = document.getElementById('myAjaxUploader_FileItemInfo_' + arr[2]);
            
            
            return mainSpan.getElementsByTagName('span')[0].innerHTML;
           
        }

        function handleFileDrop(evt) {
            evt.stopPropagation();
            evt.preventDefault();

            var files = evt.dataTransfer.files; // FileList object.

            // files is a FileList of File objects. List some properties.
            var output = [];
            for (var i = 0, f; f = files[i]; i++) {
                // Only process image files.
                if (!f.type.match('image.*')) {
                    continue;
                }
                
                var reader = new FileReader();

                // Closure to capture the file information.
                reader.onload = (function (theFile) {
                    return function (e) {
                        // Render thumbnail.
                        var span = document.createElement('span');                      
                     

                        span.innerHTML = ['<img id=' + escape(theFile.name) +
                            ' class="Img" style="padding:5px;border : 1px solid grey;height:100px;width:100px;" " src="', e.target.result,
                                          '" title="', escape(theFile.name), '"/>'].join('');

                        document.getElementById('list').insertBefore(span, null);
                    };
                })(f);

                // Read in the image file as a data URL.
                reader.readAsDataURL(f);
            }

            
           
        }

        

    </script>
</head>

<body>
    <form id="frmMain" runat="server">
    <ajaxToolkit:ToolkitScriptManager  ID="smMain" runat="server" EnablePartialRendering = "true">
</ajaxToolkit:ToolkitScriptManager>
<asp:Button ID="btnShow" runat="server" Text="Show Modal Popup" />



<!-- ModalPopupExtender -->
<ajaxToolkit:modalpopupextender ID="mpeFileUpload" runat="server" PopupControlID="modalPop" TargetControlID="btnShow"
    CancelControlID="btnClose" BackgroundCssClass="modalBackground">
</ajaxToolkit:modalpopupextender>
<div id="modalPop" runat="server" class="Modal" align="center" style="display:none" >
    <div class="Header"><div class="CloseButton" ><asp:ImageButton ID="btnClose" style="height:16px;width:16px;" runat="server" ImageUrl="~/Images/Close.png" /></div>
        <b>Image Uploader using AjaxFileUpload and ModalPopup in ASP.NET</b>
    </div>
    
    <br />
    <!-- AjaxFileUpload -->
   <ajaxToolkit:AjaxFileUpload ID="myAjaxUploader"
    ThrobberID="myThrobber"
    ContextKeys="fred"
    AllowedFileTypes="jpg,jpeg"
    MaximumNumberOfFiles="5"           
    runat="server"/>

    

  <output id="list"></output>
</div>
       

    </form>
</body>
</html>


Remember to add Reference to AjaxControlToolKit and add the following in web.config for AjaxFileUpload to work. You can download AjaxControlToolKit from https://ajaxcontroltoolkit.codeplex.com/

<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <add name="AjaxFileUploadHandler" verb="*"
        path="AjaxFileUploadHandler.axd"
        type="AjaxControlToolkit.AjaxFileUploadHandler, 
          AjaxControlToolkit"/>
    </handlers>
  </system.webServer>


Step Three: Running the Web Site. Tested in Google Chrome and IE 11 

1) Click on the Show Modal Popup button
2) Drop Image files to the zone "Drop Files Here"




3) You can see the Images to be uploaded and their preview in thumbnails
4) Click on the Delete button to remove it from the queue and thumbnails
















5) Click on Upload button to upload files. You must handle this from the Server Code.