File upload without refreshing the page - Ajax File Upload

When we use file upload control in web pages, it required to post the page to get the file uploaded. Below I describe how to upload a file without refreshing the page with better looking upload control.

Supported Browseres : Chrome, IE (6,7,8,9), Firefox, Safari

Demo : Upload without page refresh
Ajax Uploader Script : uploader.js

Our control will look like

HTML Markup

This is our div control that will be converted to a upload control.
<div id="fileUploaderContainer" class="fileuploadcontainer"></div>

Need a button to upload selected files.
<input id="uploadbtn" type="button" value="upload" />

Page Load Script

We need to add following script to be called when page is loaded. So that it will wire up required events for the file upload and generate controls dynamically in side the given control ("fileUploaderContainer").


    $(document).ready(function () {

        $("#fileUploaderContainer").prepareAjaxUpload(

        {
            url: '../FileUpload/Upload',

            buttonImageUrl: '/images/fileUpload.png',

            viewStyle: 'fileuploadviewitem',
            browseStyle: 'fileuploadbutton',
            successStyle: 'fileuploadviewitemsuccess',
            errorStyle: 'fileuploadviewitemerror',
            onComplete: function (data) {
                if (data != null) {
                    //success upload : Do something if required
                }
                else {
                    //Error upload : show error 
                    alert('No file uploaded');
                }
            }
        });

        $("#uploadbtn").click(function () {

            $("#fileUploaderContainer").upload();
        });

    });


Upload Control Implementation in jquery

$.fn.prepareAjaxUpload = function (options) {

    this.constructor.prototype.uploadOptions = { url: '../FileUpload/Upload' };
    var uploadPath = options == null || options.url == undefined || options.url == null || options.url == '' ? this.uploadOptions.url : options.url;
    var viewStyle = options == null || options.viewStyle == undefined || options.viewStyle == null || options.viewStyle == '' ? null : options.viewStyle;
    var browseStyle = options == null || options.browseStyle == undefined || options.browseStyle == null || options.browseStyle == '' ? null : options.browseStyle;
    var uploadStyle = options == null || options.uploadStyle == undefined || options.uploadStyle == null || options.uploadStyle == '' ? null : options.uploadStyle;
    var successStyle = options == null || options.successStyle == undefined || options.successStyle == null || options.successStyle == '' ? null : options.successStyle;
    var errorStyle = options == null || options.errorStyle == undefined || options.errorStyle == null || options.errorStyle == '' ? null : options.errorStyle;
    var onComplete = options == null || options.onComplete == undefined || options.onComplete == null ? null : options.onComplete;
    var buttonImageUrl = options == null || options.buttonImageUrl == undefined || options.buttonImageUrl == null ? null : options.buttonImageUrl;
    $(this).empty();
    var fileupdcount = ($('input[type="file"]').length + 1).toString();
    var fileuploaderid = 'fileupload' + fileupdcount;
    var fileuploaderfrmid = 'fileuploadfrm' + fileupdcount;
    var fileuploaderframeid = 'fileuploadframe' + fileupdcount;
    var fileuploadpostbtnid = 'fileuploadpostbtn' + fileupdcount;

    var uploadform = document.createElement('form');
    $(uploadform).attr('method', 'post');
    $(uploadform).attr('id', fileuploaderfrmid);
    $(uploadform).attr('name', 'nm' + fileuploaderfrmid);
    $(uploadform).attr('action', uploadPath);
    $(uploadform).attr('enctype', 'multipart/form-data');
    $(uploadform).attr('target', 'nm' + fileuploaderframeid);

    var upload = document.createElement('input');
    $(upload).attr('type', 'file');
    $(upload).attr('name', 'nm' + fileuploaderid);
    $(upload).attr('id', fileuploaderid);
    if (uploadStyle == null || uploadStyle == '') {
        $(upload).attr('style', 'cursor:pointer;position:relative;height: 34px;min-height: 34px;width:70px;max-width:70px;line-height:30px;z-index:2px;margin-left:-2px;margin-top:-1px;');
    }
    else {
        $(upload).addClass(uploadStyle);
    }
    $(upload).css('opacity', '0');
    $(upload).css('-moz-opacity', '0');
    $(upload).css('filter', 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)');

    var uploadview = document.createElement('div');
    if (viewStyle == null || viewStyle == '') {
        $(uploadview).attr('style', 'border: 1px solid #CFCFCF;background-color: #F7F7F7;height:32px;vertical-align:middle;margin:0;padding: 0px 10px 0px 10px;display:inline-block;float:left;border-collapse:collapse;color:#C5BFBF;line-height:32px;font-family:Tahoma;font-size:13px;letter-spacing:1px;overflow-x:hidden;overflow-y:scroll;');
    }
    else {
        $(uploadview).addClass(viewStyle);
    }
    $(uploadview).html('No File');
    $(upload).wrap(uploadview);

    var browseBtn = document.createElement('div');
    if (viewStyle == null || viewStyle == '') {
        $(browseBtn).attr('style','border: 1px solid #8B8282;position:relative;display:inline-block;float:left;border-collapse:collapse;cursor:pointer;width:32px;height:32px;');
    }
    else {
        $(browseBtn).addClass(browseStyle);
    }
    $(browseBtn).constructor.prototype.uploaderElement = upload;
    if (buttonImageUrl != null && buttonImageUrl != '') {
        $(browseBtn).css('background-image', 'url(' + buttonImageUrl + ')');
        $(browseBtn).css('background-repeat', 'no-repeat');
    }

    $(upload).bind('change', function () {
        if (errorStyle != null && errorStyle != '') $(uploadview).removeClass(errorStyle);
        if (successStyle != null && successStyle != '') $(uploadview).removeClass(successStyle);
        $(uploadview).html($(upload).val().split(/(\\|\/)/g).pop());
    });

    this.constructor.prototype.fileUploader = upload;
    this.constructor.prototype.uploaderForm = uploadform;
    this.constructor.prototype.uploaderView = uploadview;
    this.constructor.prototype.postButtonId = fileuploadpostbtnid;
    this.constructor.prototype.upload = function () {
        if ($(upload).val() != null && $(upload).val() != '') {
            $("#" + fileuploaderfrmid).submit();
        }
    };

    var ifrmsHtml = '';
    var frmcontainer = document.createElement('div');
    $(frmcontainer).html(ifrmsHtml);
    $(browseBtn).append(upload);
    $(uploadform).append(uploadview);
    $(uploadform).append(browseBtn);
    $(uploadform).append(frmcontainer);
    $(this).append(uploadform);

    var iframe = $("#" + fileuploaderframeid);
    iframe.constructor.prototype.uploaderView = uploadview;
    iframe.constructor.prototype.fileUploader = upload;
    iframe.constructor.prototype.onComplete = onComplete;

    $(uploadform).submit(function () {
        this.target = iframe.attr("name");
        iframe.get(0).processContent = true; // The use of this flag will be explained
    });

    $(iframe).load(function () {
        debugger;
        var iframeDocument = this.contentWindow || this.contentDocument;
        iframeDocument = iframeDocument.document ? iframeDocument.document : iframeDocument;
        var data = $('body', iframeDocument).html();
        var objRes = null;
        if (data != null && data != '') {
            var jsntext = data.substring(data.indexOf('{'), data.indexOf('}') + 1)
            objRes = jQuery.parseJSON(jsntext);
        }
        if (objRes != null) {
            if (objRes.Result == 'Success') {
                if ($.browser.msie) {
                    var uploadClone = $(upload).clone();
                    $(upload).replaceWith(uploadClone);
                    upload = uploadClone;
                    $(upload).bind('change', function () {
                        if (errorStyle != null && errorStyle != '') $(uploadview).removeClass(errorStyle);
                        if (successStyle != null && successStyle != '') $(uploadview).removeClass(successStyle);
                        $(uploadview).html($(upload).val().split(/(\\|\/)/g).pop());
                    });
                }
                else {
                    $(upload).val('');
                }
                $($(this).uploaderView).html('Completed');
                if (successStyle != null && successStyle != '') $(uploadview).addClass(successStyle);
                if (errorStyle != null && errorStyle != '') $(uploadview).removeClass(errorStyle);
            }
            else {
                $($(this).uploaderView).html('Error');
                if (errorStyle != null && errorStyle != '') $(uploadview).addClass(errorStyle);
                $if(successStyle != null && successStyle != '')(uploadview).removeClass(successStyle);
            }
            if ($(this).onComplete != null && $(this).onComplete != undefined) {
                $(this).onComplete(objRes);
            }
        }
    });

}


Sample Styles


.fileuploadcontainer
{
width:310px;
display:inline-block;
height:auto;
}

.fileuploadviewitem

{
border: 1px solid #CFCFCF;
background-color: #F7F7F7;
width:250px;
height:32px;
vertical-align:middle;
margin:0;
padding: 0px 10px 0px 10px;
display:inline-block;
float:left;
border-collapse:collapse;
color:#C5BFBF;
line-height:32px;
font-family:Tahoma;
font-size:13px;
letter-spacing:1px;
overflow-x:hidden;
overflow-y:scroll;
}

.fileuploadbutton

{
    border: 1px solid #8B8282;
position:relative;
display:inline-block;
float:left;
border-collapse:collapse;
cursor:pointer;
width:32px;
height:32px;
background-image:url(../../images/fileUpload.png);
overflow:hidden;
}

.uploaderinvisible

{
    cursor:pointer;    
position:relative;
    height: 34px;
    min-height: 34px;
width:70px;
max-width:70px;
line-height:30px;
z-index:2px;
margin-left:-2px;    
margin-top:-1px;    
    opacity: 0;
    -moz-opacity: 0;
    filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);
}

.fileuploadviewitemsuccess

{
    background-color: #E9FFD8;
    color: #149C19;
}

.fileuploadviewitemerror

{
    background-color: #FFF0F0;
    color: #E65454;
}

.invisibaleiframe

{
border:none;
margin:0;
padding:0;
overflow:visible;
height:auto;
width:auto;
}

Resources

File upload icon 

Jquery :  jquery-1.8.3.min.js


Comments

Popular posts from this blog

Embedding PowerBI with ASP.NET Core 2 and Angular(2,4,5)

Handling Exit Event of Console Application in C#

Taxi - Cab services in Colombo - Sri Lanka