js上传

有时候需要显示进度,这时候就需要做一些切割,具体上传代码如下:

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="http://cdn.bootcss.com/jquery/2.2.4/jquery.js"></script>
</head>
<body>
    <input type="file" name="my_big_file" id="my_big_file" />
    <input type="button" value="上传" id="upload_btn" />
    <div id="tip"></div>

    <script type="text/javascript">
        $(function(){
            //页面加载完毕后开始执行的事件
            $("#upload_btn").click(function(){
                if($("#my_big_file").val()=="")
                {
                    console.log("请选择文件");return false;
                }
                var file= document.getElementById("my_big_file").files[0];
                var total_size=file.size;
                var step=1024*1024;
                var num=Math.ceil(total_size/step);
                var has_loaded=0;
                for(var i=0;i<num;i++)
                {
                    has_loaded+=step;
                    //var reader= new FileReader();
                    //reader.readAsBinaryString(file.slice(has_loaded,has_loaded+step));
                    $("#tip").html("当前进度 "+has_loaded/total_size*100+"%");
                    sleep(10);
                    console.log("当前进度 "+has_loaded/total_size*100+"%");
                    //reader.onprogress=function(e){
                        //console.log(this.result);
                        //console.log("当前进度 "+has_loaded/total_size*100+"%");
                    //};
                }
            });
        });
        function sleep(numberMillis) { 
            var now = new Date(); 
            var exitTime = now.getTime() + numberMillis; 
            while (true)
            {
                now = new Date();
                if (now.getTime() > exitTime)
                {
                    return;
                }
            }
        }    
</script>
</body>
</html>

 

posted @ 2019-03-29 11:54  李照耀  阅读(731)  评论(0编辑  收藏  举报