Ajax 文件上传进度监听之upload.onprogress Ajax 文件上传进度监听之upload.onprogress案例详解
Henry_ww 人气:0想了解Ajax 文件上传进度监听之upload.onprogress案例详解的相关内容吗,Henry_ww在本文为您仔细讲解Ajax 文件上传进度监听之upload.onprogress的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:ajax,upload.onprogress,ajax,upload.onprogress文件上传进去监听,下面大家一起来学习吧。
$.ajax实现
<!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>Document</title> <script src="./libs/jquery/jquery.js"></script> <style> div { width: 0%; height: 20px; background-color: #f00; /* transition: all 0.2s; */ } </style> </head> <body> <div></div> <input type="file" /> <script> $(function() { // 用户选择好文件之后单击弹出层的“打开”按钮的触发事件是:change $('input').on('change', function() { // 1.收集文件数据 let myfile = $('input')[0].files[0] let formdata = new FormData() formdata.append('file_data', myfile) // 2.发起ajax请求 $.ajax({ url: 'http://127.0.0.1:3001/uploadFile', type: 'post', data: formdata, processData: false, contentType: false, xhr: function() { let newxhr = new XMLHttpRequest() // 添加文件上传的监听 // onprogress:进度监听事件,只要上传文件的进度发生了变化,就会自动的触发这个事件 newxhr.upload.onprogress = function(e) { console.log(e) let percent = (e.loaded / e.total) * 100 + '%' $('div').css('width', percent) } return newxhr }, success: function(res) { console.log(res) }, dataType: 'json' }) }) }) </script> </body> </html>
原生实现:
<!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>Document</title> <script src="./libs/jquery/jquery.js"></script> <style> div { width: 0%; height: 20px; background-color: #f00; /* transition: all 0.2s; */ } </style> </head> <body> <div></div> <input type="file" /> <script> $(function() { // 用户选择好文件之后单击弹出层的“打开”按钮的触发事件是:change $('input').on('change', function() { // 1.收集文件数据 let myfile = $('input')[0].files[0] let formdata = new FormData() formdata.append('file_data', myfile) let xhr = new XMLHttpRequest() xhr.open('post', 'http://127.0.0.1:3001/uploadFile') // 细节1:文件上传,如果使用fromdata,则不要设置请求头 xhr.upload.onprogress = function(e) { console.log(e) let percent = (e.loaded / e.total) * 100 + '%' $('div').css('width', percent) } // 细节2:send中可以直接传递formdata xhr.send(formdata) }) }) </script> </body> </html>
加载全部内容