1. 程式人生 > >JS 檔案讀取的進度條顯示方法(FileReader、onprogress)——20181116

JS 檔案讀取的進度條顯示方法(FileReader、onprogress)——20181116

這裡FileReader只是從磁碟把檔案讀取到瀏覽器,並沒有傳送到伺服器。參考連結1       參考連結2

<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<style>
#uploadProgress{
  position: relative;
  width: 100%;
  height: 30px;
  background-color: #ddd;
}

#upload{
  position: absolute;
  width: 0%;
  height: 100%;
  background-color: #4CAF50;
}

#label{
  text-align: center;
  line-height: 30px;
  color: white;
}
</style>
</head>

<body>
    檔案瀏覽:
    <input type="file" id="files" multiple />
    <input type="button" value="檔案上傳" onclick="readerBinary();" />
    <br/>
    <input type="button" value="顯示檔案資訊" onclick="showdatelists();" />
	<div id="uploadProgress">
		<div id="upload">
			<div id="label">0%</div>
		</div>
	</div>

    <script>
    	var showdatelists = function () {
        var imageEle = document.getElementById("files");
		var filelist = imageEle.files;
		for (var i = 0; i < filelist.length; i++)
			{
        	var file = filelist[i];
        	div = document.createElement("div");
        	div.innerHTML = "第" + (i + 1) + "個檔名字是:" + file.name + ",檔案大小是:" + file.size + "檔案型別是:" + file.type;
        	document.body.appendChild(div);
         	}
        }

        
        
        var readerBinary = function(){
		var elem = document.getElementById("upload");   
		var width = 0;

		var reader = null;
		if (FileReader) {
			reader = new FileReader();
		}
		else {
			alert("不支援");
		}
		reader.readAsText(document.getElementById("files").files[0]);
		var max = document.getElementById("files").files[0].size;
		//讀取不中斷則觸發該事件
		reader.onprogress = function (evt)
		{
			elem.style.width = evt.loaded/max*100 + '%';
			document.getElementById("label").innerHTML = evt.loaded/max*100 + '%';
		}
      	} 
    </script>
</body>
</html>

顯示效果: