Ajax native ajax-xhr object file upload progress bar case

<input type='file' > 浏览文件夹

document.querySelector ( 'input') files; . obtained file object file set objects
xhr.onload.progress = function () {}; callback function also upload progress
event.lengthComputable; weights and measures progress, returns to 100% false, otherwise return to true;
event.loaded; uploaded the file size
event.total; total file size
(event.loaded / event.total) * 100; file upload progress, the progress bar value assigned to the dynamic change

Reception:

<html>
<head>
	<meta charset="utf-8">
	<title></title>
	<script src="jquery-3.4.1.js"></script>
</head>
<body>

<progress min="0" max="100" value="0"></progress>
<input type="file" class='tempFile' multiple >
<button onclick='ajax()'>上传文件</button>
	<script>

		function ajax()
		{
			var files=document.querySelector('.tempFile').files;

			//get小于1M的数据
			var data=new FormData();
			for(var i=0;i<files.length;i++)
			{
				var file=files[i];
				data.append("file"+i+":",file);
			}

			//ajax上传
			var xhr=new XMLHttpRequest();
			xhr.onreadystatechange=function()
			{
				if(xhr.readyState==4)
				{
					
					if(xhr.status==200)
					{
						
						console.log(xhr.responseText);
					}
				}
			}

			var progress=document.querySelector("progress");
			//上传的进度回调
			xhr.upload.onprogress=function(event){

				//长度度量返回布尔值,100%为false,否则为true
				if(event.lengthComputable)
				{
					//当前进度为上传部分/总长度
					
					progress.value=(event.loaded/event.total)*100;
				}
			 };

			//发送
			xhr.open('post','3.php',true);
			xhr.send(data);
		}
	</script>
	
</body>

</html>

Backstage:

<?php


	echo json_encode($_POST);

?>

Published 252 original articles · won praise 3 · Views 3267

Guess you like

Origin blog.csdn.net/weixin_43294560/article/details/103658040