2013-02-23 120 views
0

我需要一些幫助以滿足以下要求。在javascript中下載和合並多部分文件

  • 從web服務器下載巨大的多部分csv文件,然後在打開用戶之前在客戶端加入這些部分。
  • 我可以在下載之前獲取零件的數量並從網絡服務器獲取它們的URL。
  • 我需要在客戶端瀏覽器中做到這一點,因此我認爲JavaScript是最好的選擇。
  • 用戶使用IE作爲主要瀏覽器,但我不能要求他們改變安全設置(VBScript中/ activxcontrol將無法正常工作)
+0

「從網絡服務器下載龐大的多csv文件,並打開它之前加入在客戶端的部分用戶「幾乎是不這樣做的原因。如果用戶必須下載一個龐大的數據集,那麼您的解決方案並不是正確的解決方案。讓客戶端向服務器詢問用戶實際可以看到的位,然後編寫代碼來處理這些問題,而不是需要一個巨大的數據。 – 2013-02-23 16:34:26

+0

我完全同意你的看法。但應用程序已經在那裏。今天用戶手動合併文件。我只是試圖自動化該部分。 – user2102619 2013-02-23 18:11:01

回答

0

如果你沒有選擇,只能與這個工作,你可以使用一個集合:

var data; // will contain the retrieved data 

/** 
* Grab data from the first URL in the list, adding it 
* to the global data variable. If the list is empty, 
* we got all the data and we succeed. If an XHR fails, we fail. 
*/ 
function prepData(urlList, success, fail) { 
    if(urlList.length===0) { 
    succes(); // wrap in timeout if you need to break out of call chain 
    return; 
    } 
    var xhr = new XMLHttpRequest(); 
    var url = urlList.splice(0,1)[0]; 
    xhr.open("GET", url, true); 
    xhr.onreadystatechange = function() { 
    if (xhr.status === 200 && xhr.readyState === 4) { 
     data += xhr.responseText; 
     prepData(urlList, success, fail); 
    } else { 
     fail(urlList, xhr); // again, wrap in timeout to break out of call chain 
    } 
    } 
} 

我們可以再用類似的代碼調用此:

/** 
* prepare our data prior to application "start" 
*/ 
prepData(['...','...','...'], function(){ 
    console.log("finished aggregating data"); 
    // all went well. Start the actual data-consuming code 
}, function(notLoadedList, failedXhrObject){ 
    console.log("ohnoes!", notLoadedList, failedXhrObject); 
    // something went wrong, and we can fail gracefully 
});