使用单个操作下载多个文件

132

我不确定是否可以使用标准的Web技术实现这一点。

我想让用户能够在单个操作中下载多个文件。也就是说,点击文件旁边的复选框,然后获取所有选中的文件。

如果可能的话,你推荐什么基本策略?我知道我可以使用comet技术创建服务器端事件来触发HttpResponse,但我希望有更简单的方法。


你可以运行这个程序两次,它能正常工作。 - theshubhagrwl
19个回答

3
为了解决这个问题,我创建了一个JS库,在客户端直接将多个文件流式传输到zip中。其主要独特功能是没有内存大小限制(一切都是流式的),也没有zip格式限制(如果内容超过4GB,则使用zip64)。
由于它不进行压缩,因此性能非常高效。
npmgithub上查找“downzip”!

1

迄今为止最简单的解决方案(至少在ubuntu/linux中):

  • 创建一个文本文件,其中包含要下载的文件的URL(即file.txt)
  • 将“file.txt”放置在要下载文件的目录中
  • 打开先前行中下载目录中的终端
  • 使用命令“wget -i file.txt”下载文件

操作起来非常容易。


我不明白为什么这个被踩了。这个完美地运行了,非常感谢。 - Martin Fürholz
1
它不太用户友好。 - Frazer Kirkman

1

为了改进@Dmitry Nogin的答案:这对我很管用。

然而,由于我不确定文件对话框在各种操作系统/浏览器组合上的工作方式,因此它未经测试。(因此是社区wiki。)

<script>
$('#download').click(function () {
    download(['http://www.arcelormittal.com/ostrava/doc/cv.doc', 
              'http://www.arcelormittal.com/ostrava/doc/cv.doc']);
});

var download = function (ar) {
    var prevfun=function(){};
    ar.forEach(function(address) {  
        var pp=prevfun;
        var fun=function() {
                var iframe = $('<iframe style="visibility: collapse;"></iframe>');
                $('body').append(iframe);
                var content = iframe[0].contentDocument;
                var form = '<form action="' + address + '" method="POST"></form>';
                content.write(form);
                $(form).submit();
                setTimeout(function() {    
                    $(document).one('mousemove', function() { //<--slightly hacky!
                        iframe.remove();
                        pp();
                    });
                },2000);
        }
        prevfun=fun; 
      });
      prevfun();   
}
</script>

0
以下代码百分之百有效。 第一步:将以下代码粘贴到index.html文件中。
<!DOCTYPE html>
<html ng-app="ang">

<head>
    <title>Angular Test</title>
    <meta charset="utf-8" />
</head>

<body>
    <div ng-controller="myController">
        <button ng-click="files()">Download All</button>
    </div>

    <script src="angular.min.js"></script>
    <script src="index.js"></script>
</body>

</html>

步骤2:将以下代码粘贴到index.js文件中

"use strict";

var x = angular.module('ang', []);

    x.controller('myController', function ($scope, $http) {
        var arr = [
            {file:"http://localhost/angularProject/w3logo.jpg", fileName: "imageone"},
            {file:"http://localhost/angularProject/cv.doc", fileName: "imagetwo"},
            {file:"http://localhost/angularProject/91.png", fileName: "imagethree"}
        ];

        $scope.files = function() {
            angular.forEach(arr, function(val, key) {
                $http.get(val.file)
                .then(function onSuccess(response) {
                    console.log('res', response);
                    var link = document.createElement('a');
                    link.setAttribute('download', val.fileName);
                    link.setAttribute('href', val.file);
                    link.style.display = 'none';
                    document.body.appendChild(link);
                    link.click(); 
                    document.body.removeChild(link);
                })
                .catch(function onError(error) {
                    console.log('error', error);
                })
            })
        };
    });

注意:确保将要下载的三个文件与 angularProject/index.htmlangularProject/index.js 文件放置在同一文件夹中。


1
你真的需要《最后的气宗》这个东西吗? - B''H Bi'ezras -- Boruch Hashem

0

通过ajax调用获取url列表,然后使用jquery插件并行下载多个文件。

  $.ajax({
        type: "POST",
        url: URL,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: data,
        async: true,
        cache: false,
        beforeSend: function () {
            blockUI("body");
        },
        complete: function () { unblockUI("body"); },
        success: function (data) {
           //here data --> contains list of urls with comma seperated
            var listUrls= data.DownloadFilePaths.split(',');
            listUrls.forEach(function (url) {
                $.fileDownload(url);
            });
            return false; 
        },
        error: function (result) {
            $('#mdlNoDataExist').modal('show');
        }

    });

0

使用Ajax组件时,可以启动多个下载。因此,您必须使用https://cwiki.apache.org/confluence/display/WICKET/AJAX+update+and+file+download+in+one+blow

在您的页面或其他地方添加一个AJAXDownload实例。创建一个AjaxButton并覆盖onSubmit。创建一个AbstractAjaxTimerBehavior并开始下载。

        button = new AjaxButton("button2") {

        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form)
        {
            MultiSitePage.this.info(this);
            target.add(form);

            form.add(new AbstractAjaxTimerBehavior(Duration.milliseconds(1)) {

                @Override
                protected void onTimer(AjaxRequestTarget target) {
                    download.initiate(target);
                }

            });     
        }

下载愉快!


JavaScript?!?!?!?! - B''H Bi'ezras -- Boruch Hashem

0

我正在寻找一个解决方案来完成这个任务,但是在JavaScript中解压文件并不像我想象的那么干净。因此,我决定将这些文件封装到单个SVG文件中。

如果您已经将文件存储在服务器上(我没有),您可以简单地在SVG中设置href。

在我的情况下,我将把文件转换为base64格式并嵌入到SVG中。

编辑:SVG效果非常好。如果您只需要下载文件,则ZIP可能更好。如果您要显示文件,则SVG似乎更优秀。


0

这是我处理的方式。我打开多个ZIP文件,还有其他类型的数据(我将项目导出为PDF,并同时生成许多带有文档的ZIP文件)。

我只需复制并粘贴我的代码的一部分。 从列表中的按钮调用:

$url_pdf = "pdf.php?id=7";
$url_zip1 = "zip.php?id=8";
$url_zip2 = "zip.php?id=9";
$btn_pdf = "<a href=\"javascript:;\" onClick=\"return open_multiple('','".$url_pdf.",".$url_zip1.",".$url_zip2."');\">\n";
$btn_pdf .= "<img src=\"../../../images/icones/pdf.png\" alt=\"Ver\">\n";
$btn_pdf .= "</a>\n"

所以,一个基本的调用JS例程(Vanilla规则!)。 这是JS例程:

 function open_multiple(base,url_publication)
 {
     // URL of pages to open are coma separated
     tab_url = url_publication.split(",");
     var nb = tab_url.length;
     // Loop against URL    
     for (var x = 0; x < nb; x++)
     {
        window.open(tab_url[x]);
      }

     // Base is the dest of the caller page as
     // sometimes I need it to refresh
     if (base != "")
      {
        window.location.href  = base;
      }
   }

诀窍在于不要直接提供ZIP文件的链接,而是将其发送到浏览器。就像这样:

  $type_mime = "application/zip, application/x-compressed-zip";
 $the_mime = "Content-type: ".$type_mime;
 $tdoc_size = filesize ($the_zip_path);
 $the_length = "Content-Length: " . $tdoc_size;
 $tdoc_nom = "Pesquisa.zip";
 $the_content_disposition = "Content-Disposition: attachment; filename=\"".$tdoc_nom."\"";

  header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
  header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");   // Date in the past
  header($the_mime);
  header($the_length);
  header($the_content_disposition);

  // Clear the cache or some "sh..." will be added
  ob_clean();
  flush();
  readfile($the_zip_path);
  exit();

-1
           <p class="style1">



<a onclick="downloadAll(window.links)">Balance Sheet Year 2014-2015</a>

</p>

<script>
 var links = [
  'pdfs/IMG.pdf',
  'pdfs/IMG_0001.pdf',
 'pdfs/IMG_0002.pdf',
 'pdfs/IMG_0003.pdf',
'pdfs/IMG_0004.pdf',
'pdfs/IMG_0005.pdf',
 'pdfs/IMG_0006.pdf'

];

function downloadAll(urls) {
  var link = document.createElement('a');

  link.setAttribute('download','Balance Sheet Year 2014-2015');
  link.style.display = 'none';

  document.body.appendChild(link);

  for (var i = 0; i < urls.length; i++) {
    link.setAttribute('href', urls[i]);
    link.click();
  }

  document.body.removeChild(link);
}
</script>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接