1. 程式人生 > >前端檔案上傳,獲取進度

前端檔案上傳,獲取進度

陳年老問題了,記錄一下,XMLHttpRequest.upload

主要就是 xhr.onprogress 與 xhr.upload.onprogress 

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<input type="file" id="btn">
<script>
	btn.onchange = function (e) {
		const formData = new FormData();
		formData.append('file', e.target.files[0]);
		const xhr = new XMLHttpRequest();
		xhr.onprogress = function (e) {
			console.log('xhr.onprogress', '我只在上傳結束觸發');
			console.log(e.loaded);
			console.log(e.total);
		};
		xhr.upload.onprogress = function (e) {
			console.log('xhr.onprogress', '我在上傳時多次觸發');
			console.log(e.loaded / e.total);
		};
		xhr.open('post', 'demo.php');
		xhr.send(formData)
	}
</script>
</body>
</html>
// demo.php
<?php
$file = $_FILES['file'];
echo json_encode($file);