2015-10-13 56 views
0

我使用XMLHttpRequest方法從服務器獲取單個圖像的URL以下載,保存並從android本地存儲中檢索它,並且我已成功獲取它爲單個圖像網址工作;現在,我決定用一種方法從服務器上下載多個圖像。任何人都可以讓我看到一兩種方式嗎?使用javascript從XMLHttpRequest服務器下載多個圖像使用javascript

在此先感謝!

在這裏,我正在使用它來下載一個圖像

 var xhr = new XMLHttpRequest(); 

     xhr.open('GET', url, true); 

     xhr.responseType = "blob"; 
     console.log(xhr); 

     xhr.onload = function (e) { 
      console.log(e); 
      if (xhr.readyState == 4) { 
       console.log(xhr.response); 
       // if (success) success(xhr.response); 
       saveFile(xhr.response, 'images'); 
      } 
     }; 
     xhr.send(); 

回答

0

假設你有URL列表從圖片可以下載代碼,你可以使用一個簡單for循環和存儲XMLHttpRequest變量數組。

var xhrList = []; 
var urlList = ['example.com/image1', 
       'example.com/image2', 
       'example.com/image2']; 
for (var i=0; i< urlList.length; i++){ 
    xhrList[i] = new XMLHttpRequest(); 

    xhrList[i].open('GET', urlList[i], true); 

    xhrList[i].responseType = "blob"; 
    console.log(xhrList[i]); 

    xhrList[i].onload = function (e) { 
     console.log(e); 
     if (this.readyState == 4) { 
      console.log(this.response); 
      // if (success) success(this.response); 
      saveFile(this.response, 'images'); 
     } 
    }; 
    xhrList[i].send(); 
} 
+0

這真的是一個很有價值的答案,但如果我在服務器中有更大的圖像集合呢?我是否需要粘貼我想要使用的每個網址? @hkbharath –

+0

如果您有大量圖像,請再添加一個請求以從服務器獲取URL列表。將所有圖像放在同一個文件夾中,然後編寫一個簡單的服務器端腳本來獲取該文件夾中的圖像列表列表。將該列表發送給客戶端。 !確保您只有在獲得完整列表文件後纔開始加載圖像! – hkbharath

+0

現在我只有9個圖像要顯示在同一個文件夾中,但稍後會有100張圖片。有沒有一種方法,我可以採取什麼是@hkbharath,與URL調用文件夾?另一件事是它將所有圖像捆綁在一個文件名中,並且找不到分離它們並單獨保存的方法。我嘗試了這樣但仍然不存在'tempString ='puolukka'+ i.toString(); console.log(tempString +'是這一個'); saveFile(this.response,tempString +'.jpg'); ' –

相關問題