天天看点

ajax无刷新上传文件

详细的解释都在注释里面了,注意一点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>
           

继续阅读