詳細的解釋都在注釋裡面了,注意一點XMLHttpRequest : 增加很多功能,他不推薦使用onreadystatechange這個事件來監聽,推薦使用onload
是以我們下面采用的也是onload代替onreadystatechange
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>無标題文檔</title>
<style>
#div1 {width: 300px; height: 30px; border: 1px solid #000; position: relative;}
#div2 {width: 0; height: 30px; background: #CCC;}
#div3 {width: 300px; height: 30px; line-height: 30px; text-align: center; position: absolute; left: 0; top: 0;}
</style>
<script>
window.onload = function() {
var oBtn = document.getElementById('btn');
var oMyFile = document.getElementById('myFile');
var oDiv2 = document.getElementById('div2');
var oDiv3 = document.getElementById('div3');
oBtn.onclick = function() {
//alert(oMyFile.value); //注意:擷取到的是file控件的value值,這個内容是顯示給你看的文字,不是我們選擇的檔案
//oMyFile.files file控件中選擇的檔案清單對象
//alert(oMyFile.files);
//我們是要通過ajax把oMyFile.files[0]資料發送給後端
/*for (var attr in oMyFile.files[0]) {
console.log( attr + ' : ' + oMyFile.files[0][attr] );
}*/
var xhr = new XMLHttpRequest();
//
xhr.onload = function() {
alert('OK,上傳完成');
}
//alert(xhr.upload);
var oUpload = xhr.upload;
//alert(oUpload);
oUpload.onprogress = function(ev) {
console.log(ev.total + ' : ' + ev.loaded);
//ev.total(要發送的總量);ev.loaded(已發送的總量)
var iScale = ev.loaded / ev.total;
oDiv2.style.width = 300 * iScale + 'px';
oDiv3.innerHTML = iScale * 100 + '%';
}
xhr.open('post', 'post_file.php', true);
xhr.setRequestHeader('X-Request-With', 'XMLHttpRequest');
var oFormData = new FormData(); //通過FormData來建構送出資料
oFormData.append('file', oMyFile.files[0]);
xhr.send(oFormData);
}
}
</script>
</head>
<body>
<input type="file" id="myFile" /><input type="button" id="btn" value="上傳" />
<div id="div1">
<div id="div2"></div>
<div id="div3">0%</div>
</div>
</body>
</html>