Ajax 檔案上傳進度監聽之upload.onprogress案例詳解
阿新 • • 發佈:2021-09-10
$.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."></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').('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>&客棧lt;/div> <input type="file" /> <script> $(function() { // 使用者選擇好檔案之後單擊彈出層的“開啟”按鈕的觸發事件是:change $('input').on('change',function() { // 1.收集檔案資料 let myfile = $('input')[0].files[0] let formdata = nwww.cppcns.comew 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>
到此這篇關於Ajax 檔案上傳進度監聽之upload.onprogress案例詳解的文章就介紹到這了,更多相關Ajax 檔案上傳進度監聽之upload.onprogress內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!