代码改变世界

Js 上传文件 页面不刷新

2014-01-06 17:57  无抿屎的牛牛  阅读(439)  评论(0编辑  收藏  举报

html控件代码:

                     <form id="form1"> 
                     <p><input type="file" name="mfile" id="mfile" />&nbsp;<input type="button" value="Upload" onclick="Submit();"  /></p> 
                     <p><label id="uploadProgress"></label></p>
                     </form>     

 

Javascript代码:

    <script>function Submit() {
            var isTrueExtension = CheckType();
            if (isTrueExtension) {
                var form = document.getElementById("form1");
                if (form["mfile"].files.length > 0)
                {
                    var file = form["mfile"].files[0];
                    var fd = new FormData();
                    //传参数
                    fd.append("afile", file);var xhr = new XMLHttpRequest();
                    xhr.open('POST', 'upload.ashx', true);

                    xhr.upload.onprogress = function (e) {
                        if (e.lengthComputable) {
                            var percentComplete = (e.loaded / e.total) * 100;
                            document.getElementById("uploadProgress").innerHTML = percentComplete + "% uploaded";
                            console.log(percentComplete + "% uploaded");
                        }
                    }
                    
                    xhr.onload = function () {
                        //上传完成状态为200
                        if (this.status == 200)
                        {
                            var a = this.response;                            
                        }
                    }

                    xhr.send(fd);
                }
            }
        }

        function CheckType() {
            //得到上传文件的值  
            var fileName = $("#mfile").val();
            //返回String对象中子字符串最后出现的位置.  
            var seat = fileName.lastIndexOf(".");

            //返回位于String对象中指定位置的子字符串并转换为小写.  
            var extension = fileName.substring(seat).toLowerCase();
            //判断允许上传的文件格式  

            var allowed = [".cclx", ".cctx", ".ccl", ".cct"];
            for (var i = 0; i < allowed.length; i++) {
                if (!(allowed[i] != extension)) {
                    return true;
                }
            }
            alert("不支持" + extension + "格式");
            return false;
        }
    </script>

 

后台upload.ashx处理代码:

        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;
            string _file = request.Files["afile"].FileName;
            request.Files["afile"].SaveAs(_file );
context.Response.Write("1"); }