Js异步上传加进度条

http://www.ruanyifeng.com/blog/2012/09/xmlhttprequest_level_2.html

 

http://www.cnblogs.com/yuanlong1012/p/5127497.html

 

https://front-js.cc/test/fileupload/

 

http://www.ruanyifeng.com/blog/2012/08/file_upload.html

 

1.客户端 upload.cshtml

<!doctype html>
<html>
<head>

    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script>
        $(function () {
            $('#btn').on('click', function () {
                var files = $('#file').get(0).files;
                var len = (files.length);
                if (len > 0) {
                    console.log(files[0]);
                    if (window.FormData) {
                        var formData = new FormData();
                        // 建立一个upload表单项,值为上传的文件
                        formData.append('upload', files[0]);
                        var xhr = new XMLHttpRequest();
                        xhr.open('POST', '/Home/UploadFile');
                        // 定义上传完成后的回调函数
                        xhr.onload = function () {
                            if (xhr.status === 200) {
                                console.log('上传成功');
                            } else {
                                console.log('出错了');
                            }
                        };
                        xhr.upload.onprogress = function (event) {
                            if (event.lengthComputable) {
                                var complete = (event.loaded / event.total * 100 | 0);
                                var progress = document.getElementById('uploadprogress');
                                progress.value = progress.innerHTML = complete;
                            }
                        };
                        xhr.send(formData);
                    }
                }

            });
        });
    </script>
</head>
<body>
    <input id='file' type='file' />
    <button id='btn'>clickme</button>
    <progress id="uploadprogress" min="0" max="100" value="0">0</progress>
</body>
</html>

  2.服务端代码

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        public ActionResult UploadFile()
        {
            if (Request.Files.Count > 0)
            {
                Request.Files[0].SaveAs( AppDomain.CurrentDomain.BaseDirectory+"\\upload\\" + Guid.NewGuid().ToString() );
            }

            return View();
        }
        /// <summary>
        /// 上传页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Upload()
        {

            return View("Upload");
        }

 

posted @ 2016-11-16 17:59  zslm___  阅读(442)  评论(0编辑  收藏  举报