Click here to Skip to main content
15,884,099 members
Articles / Web Development / ASP.NET

Asynchronous File Upload

Rate me:
Please Sign up or sign in to vote.
4.96/5 (26 votes)
13 Jun 2014CPOL12 min read 126.8K   5K   103  
An Ajax control that enables a user to upload a file asynchronously with extra data
// Register the namespace for the control.
Type.registerNamespace('MyControls.Web');

/*==================== class AjaxUploadUtil ======================*/
MyControls.Web.AjaxUploadUtil = function() { };
(function() {
    var d = document, w = window;

    /**
    * Attaches event to a dom element
    */
    MyControls.Web.AjaxUploadUtil.getResponse = function(doc) {
        var response;
        var responseType = MyControls.Web.ResponseType.Others;

        if (doc.XMLDocument) {
            // response is a xml document IE property
            response = doc.XMLDocument;
            responseType = MyControls.Web.ResponseType.XML;
        } else if (doc.body) {
            // response is html document or plain text
            response = doc.body.innerHTML;
            // If the document was sent as 'application/javascript' or
            // 'text/javascript', then the browser wraps the text in a <pre>
            // tag and performs html encoding on the contents.  In this case,
            // we need to pull the original text content from the text node's
            // nodeValue property to retrieve the unmangled content.
            // Note that IE6 only understands text/html
            if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE') {
                response = doc.body.firstChild.firstChild.nodeValue;
            }

            if (response) {
                try {
                    response = Sys.Serialization.JavaScriptSerializer.deserialize('(' + response + ')');
                    responseType = MyControls.Web.ResponseType.JSON;
                }
                catch (Error) {
                    responseType = MyControls.Web.ResponseType.Others;
                }
            } else {
                response = {};
                responseType = MyControls.Web.ResponseType.JSON;
            }
        } else {
            // response is a xml document
            var response = doc;
            responseType = MyControls.Web.ResponseType.XML;
        }

        return new MyControls.Web.Response(response, responseType);
    }
    MyControls.Web.AjaxUploadUtil.addEvent = function(el, type, fn) {
        if (w.addEventListener) {
            el.addEventListener(type, fn, false);
        }
        else if (w.attachEvent) {
            var f = function() {
                fn.call(el, w.event);
            };
            el.attachEvent('on' + type, f)
        }
    }


    /**
    * Creates and returns element from html chunk
    */
    var toElement = function() {
        var div = d.createElement('div');
        return function(html) {
            div.innerHTML = html;
            var el = div.childNodes[0];
            div.removeChild(el);
            return el;
        }
    } ();
    MyControls.Web.AjaxUploadUtil.toElement = toElement;

    MyControls.Web.AjaxUploadUtil.hasClass = function(ele, cls) {
        return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
    }
    MyControls.Web.AjaxUploadUtil.addClass = function(ele, cls) {
        if (!MyControls.Web.AjaxUploadUtil.hasClass(ele, cls)) ele.className += " " + cls;
    }
    MyControls.Web.AjaxUploadUtil.removeClass = function (ele, cls) {
        var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
        ele.className = ele.className.replace(reg, ' ');
    }

    // getOffset function copied from jQuery lib (http://jquery.com/)
    if (document.documentElement["getBoundingClientRect"]) {
        // Get Offset using getBoundingClientRect
        // http://ejohn.org/blog/getboundingclientrect-is-awesome/
        var getOffset = function(el) {
            var box = el.getBoundingClientRect(),
		        doc = el.ownerDocument,
		        body = doc.body,
		        docElem = doc.documentElement,

            // for ie 
		        clientTop = docElem.clientTop || body.clientTop || 0,
		        clientLeft = docElem.clientLeft || body.clientLeft || 0,

            // In Internet Explorer 7 getBoundingClientRect property is treated as physical,
            // while others are logical. Make all logical, like in IE8.


		        zoom = 1;

            if (body.getBoundingClientRect) {
                var bound = body.getBoundingClientRect();
                zoom = (bound.right - bound.left) / body.clientWidth || 1;
            }
            if (zoom > 1) {
                clientTop = 0;
                clientLeft = 0;
            }
            var top = box.top / zoom + (window.pageYOffset || docElem && docElem.scrollTop / zoom || body.scrollTop / zoom) - clientTop,
	            left = box.left / zoom + (window.pageXOffset || docElem && docElem.scrollLeft / zoom || body.scrollLeft / zoom) - clientLeft;

            return {
                top: top,
                left: left
            };
        }

    } else {
        // Get offset adding all offsets 
        var getOffset = function(el) {
            if (w.jQuery) {
                return jQuery(el).offset();
            }

            var top = 0, left = 0;
            do {
                top += el.offsetTop || 0;
                left += el.offsetLeft || 0;
            }
            while (el = el.offsetParent);

            return {
                left: left,
                top: top
            };
        }
    }
    MyControls.Web.AjaxUploadUtil.getOffset = getOffset;

    MyControls.Web.AjaxUploadUtil.getBox = function(el) {
        var left, right, top, bottom;
        var offset = getOffset(el);
        left = offset.left;
        top = offset.top;

        right = left + el.offsetWidth;
        bottom = top + el.offsetHeight;

        return {
            left: left,
            right: right,
            top: top,
            bottom: bottom
        };
    }

    /**
    * Crossbrowser mouse coordinates
    */
    MyControls.Web.AjaxUploadUtil.getMouseCoords = function(e) {
        // pageX/Y is not supported in IE
        // http://www.quirksmode.org/dom/w3c_cssom.html			
        if (!e.pageX && e.clientX) {
            // In Internet Explorer 7 some properties (mouse coordinates) are treated as physical,
            // while others are logical (offset).
            var zoom = 1;
            var body = document.body;

            if (body.getBoundingClientRect) {
                var bound = body.getBoundingClientRect();
                zoom = (bound.right - bound.left) / body.clientWidth;
            }

            return {
                x: e.clientX / zoom + d.body.scrollLeft + d.documentElement.scrollLeft,
                y: e.clientY / zoom + d.body.scrollTop + d.documentElement.scrollTop
            };
        }

        return {
            x: e.pageX,
            y: e.pageY
        };

    }
    /**
    * Function generates unique id
    */
    var getUID = function() {
        var id = 0;
        return function() {
            return 'ValumsAjaxUpload' + id++;
        }
    } ();
    MyControls.Web.AjaxUploadUtil.getUID = getUID;

    MyControls.Web.AjaxUploadUtil.fileFromPath = function (file) {
        return file.replace(/.*(\/|\\)/, "");
    }

    MyControls.Web.AjaxUploadUtil.getExt = function (file) {
        return (/[.]/.exec(file)) ? /[^.]+$/.exec(file.toLowerCase()) : '';
    }
})()

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) The first Ones
Jordan Jordan
-- Life is Good.
and you can make it better

Comments and Discussions