使用javascript使用XMLHttpRequest从服务器下载多个图像

download multiple images from the server with XMLHttpRequest using javascript

本文关键字:使用 图像 下载 服务器 javascript XMLHttpRequest      更新时间:2023-09-26

我使用XMLHttpRequest方法从服务器获取单个图像的url下载,保存,然后从android本地存储检索它,我已经成功地让它为单个图像url工作;现在我卡住了想办法从服务器上下载多个图像使用相同的方法。谁能给我指路吗?

提前感谢!!

这里是我用来下载单个图像的代码

        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();

假设您有一个可以下载图像的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();
}