最近有一个小需求:上传文件的时候显示上传进度(上传了百分之多少)。这个需求不难,比如以下代码就能实现:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Upload file</title> <script> function uploadFile() { var fd = new FormData(document.forms[0]); var xhr = new XMLHttpRequest(); xhr.upload.onprogress = function (e) { console.log('e.loaded:' + e.loaded + ', e.total:' + e.total) console.log(Math.round(e.loaded / e.total * 100) + '%') // 这里是上传进度 } xhr.onreadystatechange = function(){ if ( xhr.readyState === 4 ) { if ( xhr.status >= 200 && xhr.status < 300 || xhr.status === 304 ) { console.log(xhr.responseText) } } } xhr.open("POST", "/"); xhr.send(fd); } </script> </head> <body> <form action="/" method="POST" enctype="multipart/form-data"> <input type="file" name="file" id="file" required /> <input type="hidden" value="1" name="hidden"> <input type="text" name="text"> <input type="range" name="range"> <button onclick="uploadFile();" type="button" id="upload">Upload</button> </form> </body> </html>