1. 程式人生 > >實現檔案上傳的實時進度條

實現檔案上傳的實時進度條

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #outcontain{
            /*width:400px;*/
            height:30px;
            background:#ddd;
        }
         #innercontain{
            width:0px;
            height:30px;
            background:blueviolet;
            text-align: right;
        }
    </style>
</head>
<body>
    <input type="file" name="files" id="files">
    <input type="button" value="儲存" id="save">
    <p>上傳的進度</p>
    <div id="outcontain" style="width:700px">
        <div id="innercontain"></div>
    </div>
</body>
</html>
<script>
    var files=document.getElementById("files");
    var btn=document.querySelector("[type=button]");
    var innercontain=document.querySelector("#innercontain");
    var outcontain=document.querySelector("#outcontain");
    btn.onclick=function(){
             var xhr=new XMLHttpRequest();
            xhr.open("post","/files");
            / /監聽上傳進度
            xhr.upload.onprogress=function(ev){
                   // 事件物件ev
                 innercontain.style.width=(parseInt(outcontain.style.width))*(ev.loaded/ev.total)+"px";
            }
             xhr.send(files.files[0]);
             xhr.onreadystatechange=function(){
                 if(xhr.readyState==4&&xhr.status==200){
                     console.log("請求成功");
                 }
             }
    }

    
</script>