【问题标题】:Download multiples files using javascript使用javascript下载多个文件
【发布时间】:2019-07-23 22:59:26
【问题描述】:

到目前为止,我正在尝试使用 javascript 从多个 URL 下载多个文件,但我尝试了多个选项,但它仅适用于 1 个 URL。

我有一个 URL 数组,需要在浏览器中启动多个下载。

$(fileUrls).each(function(_index, fileUrl: any) {
  let tempElement: any;
  tempElement = document.createElement("A");
  tempElement.href = fileUrl;
  tempElement.download = fileUrl.substr(fileUrl.lastIndexOf("/") + 1);
  document.body.appendChild(tempElement);
  tempElement.click();
  document.body.removeChild(tempElement);
});

也尝试过使用

$(fileUrls).each(function (_index, fileUrl: any) {
  window.location.href = fileUrl;
});

但它仅适用于 1 个 URL 其余调用失败并在浏览器中显示以下警告消息

资源解释为文档,但使用 MIME 类型 application/octet-stream 传输

【问题讨论】:

    标签: javascript jquery typescript


    【解决方案1】:

    您可以使用以下代码来实现。

    创建一个数组并传递您想要的所有文件位置 下载如下。

    var files= [
          'file1_Link',
          'file2_Link',
          'file3_Link'
        ];
    

    下载所有文件的功能。我们正在创建锚标签 使用下载属性和循环,我们需要单击该链接。 请看下面的例子。

        function downloadAll(files){
        if(files.length == 0) return;
        file = files.pop();
        var theAnchor = $('<a />')
            .attr('href', file[0]) // set index accordingly
            .attr('download',file[0]) // set index accordingly
            // Firefox does not fires click if the link is outside
            // the DOM
            .appendTo('body');
    
        theAnchor[0].click(); 
        theAnchor.remove();
        downloadAll(files);
    }
    

    // 调用下面的函数来实现你的目标

    downloadAll(files);
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-03
    • 2015-10-16
    • 2018-05-26
    • 1970-01-01
    相关资源
    最近更新 更多