[請益]使用XMLHttpRequest讀檔案內容時遇到怪問

看板Web_Design作者 (小雞旦)時間9年前 (2016/04/10 23:05), 編輯推噓0(004)
留言4則, 2人參與, 最新討論串1/1
大家晚安,如題,小弟想要實做一個帶有進度條監控進度的下載功能,我使用 XMLHttpRequest 當選擇好要下載的檔案時,在onprogress state,再開另一個 XMLHttpRequest 去open我想讀取檔案的url,這個檔案裡面則填寫目前下載的 file size(byte為單位),一開始下載都還算正常,但是我的bar始終在很前面 就停住了(bar一開始有更新,後來就沒了),所以想請問板上的前輩們,我這樣的 寫法到底哪邊有不對的地方.. 以下是我的程式碼: var x = document.createElement("PROGRESS"); function updbar() { console.log('Entering updbar.....'); var rawFile = new XMLHttpRequest(); var url ="http://127.0.0.1:8080/features/FileDownload/CentralSRVDB/PXEImages/progress.txt" rawFile.open("GET", url, true); //rawFile.responseType = 'text'; rawFile.onreadystatechange = function () { console.log(rawFile.readyState); if(rawFile.readyState === 4) { if(rawFile.status === 200 || rawFile.status === 0) { var data = rawFile.responseText; var jsonResponse = JSON.parse(data); //read file console.log(TotalfileSize); console.log(jsonResponse); if(jsonResponse != 0){ x.setAttribute("max", TotalfileSize); x.setAttribute("value", jsonResponse); document.body.appendChild(x); } } } } rawFile.send(null); } var TotalfileSize=0; function TriggerProgressEvent() {//當下載檔案時會先call這支function //var progressBar = document.getElementById('p'); var xhr = new XMLHttpRequest(); //var x = document.createElement("PROGRESS"); console.log('Entering TriggerProgressEvent'); var pxe_list = document.getElementsByName("PXE_Image"); // Deal with PXE image part for(var i=0;i<pxe_list.length;i++){ //Check whether the diag pkg has selected or not if(pxe_list[i].checked == true){ console.log(pxe_list[i].value); xhr.open('GET', 'http://127.0.0.1:8080/features/FileDownload/CentralSRVDB/PXEImages/'+pxe_list[i].value,true); xhr.responseType = 'blob'; xhr.onprogress = function(event) { if(event.lengthComputable) { //console.log(event.total); //console.log(event.loaded); //x.setAttribute("max", event.total); //x.setAttribute("value", event.loaded); //document.body.appendChild(x); TotalfileSize=event.total; setTimeout(updbar, 3000 ); //3000milisecond is 3 second } }; xhr.onloadend = function(event) { //console.log(event.loaded); x.setAttribute("value", event.loaded); document.body.appendChild(x); }; xhr.send(); } } } ======================= END ====================== 麻煩大家幫我看看了,我找了很久都找不出個所以然,謝謝大家! -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 59.102.136.36 ※ 文章網址: https://www.ptt.cc/bbs/Web_Design/M.1460300746.A.A17.html

04/11 18:41, , 1F
有沒有可能是百分比沒算好?!
04/11 18:41, 1F

04/11 22:10, , 2F
回一樓,我發現是我讀取的txt file檔,一下就過了onp
04/11 22:10, 2F

04/11 22:10, , 3F
rogress階級,所以讀到的百分比永遠都是剛load進來
04/11 22:10, 3F

04/11 22:10, , 4F
的檔案的byte數
04/11 22:10, 4F
文章代碼(AID): #1N2clAeN (Web_Design)
文章代碼(AID): #1N2clAeN (Web_Design)