【问题标题】:download multiple images from the server with XMLHttpRequest using javascript使用 javascript 使用 XMLHttpRequest 从服务器下载多个图像
【发布时间】:2015-10-13 18:06:07
【问题描述】:

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

【问题讨论】:

    标签: javascript android angularjs xmlhttprequest


    【解决方案1】:

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

    【讨论】:

    • 这确实是一个有价值的答案,但是如果我在服务器中有更多的图像集合怎么办?我需要贴出我想使用的每一个网址吗? @hkbharath
    • 如果您有大量图片,则再添加一个请求以从服务器获取 URL 列表。将所有图像放在同一个文件夹中,并编写一个简单的服务器端脚本来获取该文件夹中的图像列表。将该列表发送给客户。 !!确保只有在获得完整列表文件后才开始加载图像!!!
    • 目前我只有 9 张图片要显示在同一个文件夹中,但稍后会有 100 张图片。有没有办法可以通过 url 调用获取 @hkbharath 文件夹中的内容?另一件事是它将所有图像捆绑在一个文件名中,并且找不到将它们分开并单独保存的方法。我这样尝试过,但还没有' tempString = 'puolukka' + i.toString(); console.log(tempString + '是这个'); saveFile(this.response, tempString + '.jpg'); '
    • 如果问的不是太多,您能否详细说明一下代码如何列出文件夹中的图像?谢谢@hkbharath
    猜你喜欢
    • 1970-01-01
    • 2013-03-04
    • 2017-08-06
    • 1970-01-01
    • 2012-07-15
    • 1970-01-01
    • 2012-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多