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

download multiple images from the server with XMLHttpRequest using javascript

我正在使用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();
}