js脚本实现文件上传 【原生态ajax实现】

来源:互联网 发布:广州易幻网络 编辑:程序博客网 时间:2024/05/17 01:06

需求:通过ajax保存表单,在保存表单成功后调用回调函数上传图片,这里不再使用网络上的上传插件,直接使用javascript进行上传,处理程序(ashx)进行处理,其中涉及到个浏览器的兼容性问题及方法的扩展,通过网上查找资料,写一个相对完整的实现过程

  <input class="input-file" id="fileInput" type="file">
<script type="text/javascript">        $("input[type='file']").change(function () {            uploadAndSubmit();        });        //跨浏览器获取XmlHttpRequest对象        function AjaxXmlHttpRequest() {            var xmlHttp;            try {                // Firefox, Opera 8.0+, Safari                xmlHttp = new XMLHttpRequest();            }            catch (e) {                // Internet Explorer                try {                    xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");                }                catch (e) {                    try {                        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");                    }                    catch (e) {                        alert("您的浏览器不支持AJAX!");                        return false;                    }                }            }            return xmlHttp;        }        function uploadAndSubmit() {            var fls = $("input[type='file']")[0].files;            if (fls.length > 0) {                // 寻找表单域中的 <input type="file" ... /> 标签                var file = fls[0];                // try sending                 var reader = new FileReader();                reader.onloadstart = function () {                    // 这个事件在读取开始时触发                    console.log("onloadstart");                   // document.getElementById("bytesTotal").textContent = file.size;                }                reader.onprogress = function (p) {                    // 这个事件在读取进行中定时触发                    console.log("onprogress");                   // document.getElementById("bytesRead").textContent = p.loaded;                }                reader.onload = function () {                    // 这个事件在读取成功结束后触发                    console.log("load complete");                }                reader.onloadend = function () {                    // 这个事件在读取结束后,无论成功或者失败都会触发                    if (reader.error) {                        console.log(reader.error);                    } else {                        // document.getElementById("bytesRead").textContent = file.size;                        // 构造 XMLHttpRequest 对象,发送文件 Binary 数据                        // var xhr = new XMLHttpRequest();                        var xhr = new AjaxXmlHttpRequest();                        xhr.open("POST", "../ajax/DealHtml.ashx?type=file&fileName=" + file.name);                        xhr.overrideMimeType("application/octet-stream");                        //参考网页  http://royaltutorials.com/object-has-no-method-sendasbinary/                          //大概意思是,chrome浏览器下面的XMLHttpRequest没有sendAsBinary,所以就自己给XMLHttpRequest原型定义一个这样的属性,并且这个属性是一个方法                          if (!XMLHttpRequest.prototype.sendAsBinary) {//如果XMLHttpRequest没有sendAsBinary                              XMLHttpRequest.prototype.sendAsBinary = function (datastr) {                                function byteValue(x) {                                    return x.charCodeAt(0) & 0xff;                                }                                var ords = Array.prototype.map.call(datastr, byteValue);                                var ui8a = new Uint8Array(ords);                                this.send(ui8a.buffer);                            };                        }                        xhr.sendAsBinary(reader.result);                        xhr.onreadystatechange = function () {                            if (xhr.readyState == 4) {                                if (xhr.status == 200) {                                    console.log("upload complete");                                    console.log("response: " + xhr.responseText);                                    if (xhr.responseText == "上传成功") { alert('保存成功'); }                                }                            }                        }                    }                }                //reader.readAsBinaryString(file);                // Read in the XLSX file in Binary Mode.                   //reader.readAsBinaryString(f);//<-- ***does not work if this method is used in IE10 (10.0.9200.16540C0), but works on Chrome***                   reader.readAsText(file); //<-- ***Works on both Chrome & IE10 (10.0.9200.16540C0)**            } else {                alert("Please choose a file.");            }        }    </script> 

后台处理代码:

0 0
原创粉丝点击