web-dev-qa-db-ja.com

単一のアクションで複数のファイルをダウンロードする

標準のWebテクノロジーを使用してこれが可能かどうかはわかりません。

ユーザーが1回のアクションで複数のファイルをダウンロードできるようにします。つまり、ファイルの横にあるチェックボックスをクリックし、チェックされたすべてのファイルを取得します。

それは可能ですか-もしそうなら、どのような基本戦略をお勧めしますか。コメットテクノロジーを使用してHttpResponseをトリガーするサーバー側イベントを作成できることは知っていますが、もっと簡単な方法があることを望んでいます。

99
Ankur

HTTPは、一度に複数のファイルのダウンロードをサポートしません。

2つの解決策があります。

  • X個のウィンドウを開いて、ファイルのダウンロードを開始します(これはJavaScriptで行われます)
  • 推奨ソリューションファイルを圧縮するスクリプトを作成
55
Jacob Relkin
var links = [
  'https://s3.amazonaws.com/Minecraft.Download/launcher/Minecraft.exe',
  'https://s3.amazonaws.com/Minecraft.Download/launcher/Minecraft.dmg',
  'https://s3.amazonaws.com/Minecraft.Download/launcher/Minecraft.jar'
];

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

  link.setAttribute('download', null);
  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);
}
<button onclick="downloadAll(window.links)">Test me!</button>
74
Matěj Pokorný

非表示のiframeの一時セットを作成し、GETまたはPOSTでダウンロードを開始し、ダウンロードが開始されるのを待ってiframeを削除できます。

<!DOCTYPE HTML>
<html>
<body>
  <button id="download">Download</button> 

  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
  <script type="text/javascript">

     $('#download').click(function() {
       download('http://nogin.info/cv.doc','http://nogin.info/cv.doc');
     });

     var download = function() {
       for(var i=0; i<arguments.length; i++) {
         var iframe = $('<iframe style="visibility: collapse;"></iframe>');
         $('body').append(iframe);
         var content = iframe[0].contentDocument;
         var form = '<form action="' + arguments[i] + '" method="GET"></form>';
         content.write(form);
         $('form', content).submit();
         setTimeout((function(iframe) {
           return function() { 
             iframe.remove(); 
           }
         })(iframe), 2000);
       }
     }      

  </script>
</body>
</html>

または、jQueryなし:

 function download(...urls) {
    urls.forEach(url => {
      let iframe = document.createElement('iframe');
      iframe.style.visibility = 'collapse';
      document.body.append(iframe);

      iframe.contentDocument.write(
        `<form action="${url.replace(/\"/g, '"')}" method="GET"></form>`
      );
      iframe.contentDocument.forms[0].submit();

      setTimeout(() => iframe.remove(), 2000);
    });
  }
51
Dmitry Nogin

このソリューションはブラウザー間で機能し、警告をトリガーしません。 iframeを作成するのではなく、ここで各ファイルのリンクを作成します。これにより、警告メッセージが表示されなくなります。

ループ部分を処理するには、IEで動作するために必要なsetTimeoutを使用します。

/**
 * Download a list of files.
 * @author speedplane
 */
function download_files(files) {
  function download_next(i) {
    if (i >= files.length) {
      return;
    }
    var a = document.createElement('a');
    a.href = files[i].download;
    a.target = '_parent';
    // Use a.download if available, it prevents plugins from opening.
    if ('download' in a) {
      a.download = files[i].filename;
    }
    // Add a to the doc for click to work.
    (document.body || document.documentElement).appendChild(a);
    if (a.click) {
      a.click(); // The click method is supported by most browsers.
    } else {
      $(a).click(); // Backup using jquery
    }
    // Delete the temporary link.
    a.parentNode.removeChild(a);
    // Download the next file with a small timeout. The timeout is necessary
    // for IE, which will otherwise only download the first file.
    setTimeout(function() {
      download_next(i + 1);
    }, 500);
  }
  // Initiate the first download.
  download_next(0);
}
<script>
  // Here's a live example that downloads three test text files:
  function do_dl() {
    download_files([
      { download: "http://www.nt.az/reg.txt", filename: "regs.txt" },
      { download: "https://www.w3.org/TR/PNG/iso_8859-1.txt", filename: "standards.txt" },
      { download: "http://qiime.org/_static/Examples/File_Formats/Example_Mapping_File.txt", filename: "example.txt" },
    ]);
  };
</script>
<button onclick="do_dl();">Test downloading 3 text files.</button>
31
speedplane

最も簡単な方法は、Zipファイルにまとめられた複数のファイルを提供することです。

たくさんのiframeまたはポップアップを使用して複数のファイルのダウンロードを開始できると思いますが、使いやすさの観点からは、Zipファイルの方が優れています。ブラウザが表示する10個の「名前を付けて保存」ダイアログを誰がクリックしたいのですか?

5
Thilo

IframeのjQueryバージョンは次のように答えます。

function download(files) {
    $.each(files, function(key, value) {
        $('<iframe></iframe>')
            .hide()
            .attr('src', value)
            .appendTo($('body'))
            .load(function() {
                var that = this;
                setTimeout(function() {
                    $(that).remove();
                }, 100);
            });
    });
}
4
        <!doctype html>
    <html ng-app='app'>
        <head>
            <title>
            </title>
            <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
            <link rel="stylesheet" href="style.css">
        </head>
        <body ng-cloack>        
            <div class="container" ng-controller='FirstCtrl'>           
              <table class="table table-bordered table-downloads">
                <thead>
                  <tr>
                    <th>Select</th>
                    <th>File name</th>
                    <th>Downloads</th>
                  </tr>
                </thead>
                <tbody>
                  <tr ng-repeat = 'tableData in tableDatas'>
                    <td>
                        <div class="checkbox">
                          <input type="checkbox" name="{{tableData.name}}" id="{{tableData.name}}" value="{{tableData.name}}" ng-model= 'tableData.checked' ng-change="selected()">
                        </div>
                    </td>
                    <td>{{tableData.fileName}}</td>
                    <td>
                        <a target="_self" id="download-{{tableData.name}}" ng-href="{{tableData.filePath}}" class="btn btn-success pull-right downloadable" download>download</a>
                    </td>
                  </tr>              
                </tbody>
              </table>
                <a class="btn btn-success pull-right" ng-click='downloadAll()'>download selected</a>

                <p>{{selectedone}}</p>
            </div>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
            <script src="script.js"></script>
        </body>
    </html>


app.js


var app = angular.module('app', []);            
app.controller('FirstCtrl', ['$scope','$http', '$filter', function($scope, $http, $filter){

$scope.tableDatas = [
    {name: 'value1', fileName:'file1', filePath: 'data/file1.txt', selected: true},
    {name: 'value2', fileName:'file2', filePath: 'data/file2.txt', selected: true},
    {name: 'value3', fileName:'file3', filePath: 'data/file3.txt', selected: false},
    {name: 'value4', fileName:'file4', filePath: 'data/file4.txt', selected: true},
    {name: 'value5', fileName:'file5', filePath: 'data/file5.txt', selected: true},
    {name: 'value6', fileName:'file6', filePath: 'data/file6.txt', selected: false},
  ];  
$scope.application = [];   

$scope.selected = function() {
    $scope.application = $filter('filter')($scope.tableDatas, {
      checked: true
    });
}

$scope.downloadAll = function(){
    $scope.selectedone = [];     
    angular.forEach($scope.application,function(val){
       $scope.selectedone.Push(val.name);
       $scope.id = val.name;        
       angular.element('#'+val.name).closest('tr').find('.downloadable')[0].click();
    });
}         


}]);

作業例: https://plnkr.co/edit/XynXRS7c742JPfCA3IpE?p=preview

3
suresh

Zipファイルはすてきなソリューションであることに同意します...しかし、複数のファイルをプッシュする必要がある場合、私が思いついたソリューションを以下に示します。 IE 9以上(おそらくそれよりも低いバージョンでも-テストしていません)、Firefox、Safari、Chromeで動作します。 Chromeは、サイトで初めて使用するときに複数のファイルをダウンロードするという同意を得るためのメッセージをユーザーに表示します。

function deleteIframe (iframe) {
    iframe.remove(); 
}
function createIFrame (fileURL) {
    var iframe = $('<iframe style="display:none"></iframe>');
    iframe[0].src= fileURL;
    $('body').append(iframe);
    timeout(deleteIframe, 60000, iframe);             
 }
 // This function allows to pass parameters to the function in a timeout that are 
 // frozen and that works in IE9
 function timeout(func, time) {
      var args = [];
      if (arguments.length >2) {
           args = Array.prototype.slice.call(arguments, 2);
      }
      return setTimeout(function(){ return func.apply(null, args); }, time);
 }
 // IE will process only the first one if we put no delay
 var wait = (isIE ? 1000 : 0);
 for (var i = 0; i < files.length; i++) {  
      timeout(createIFrame, wait*i, files[i]);
 }

この手法の唯一の副作用は、送信とダウンロードダイアログの表示の間に遅延が表示されることです。この影響を最小限に抑えるには、describe here とこの質問について ブラウザがファイルのダウンロードを受信したことを検出する を使用することをお勧めします。ダウンロードを開始しました。クライアント側でこのCookieを確認し、サーバー側で送信する必要があります。 Cookieに適切なパスを設定することを忘れないでください。そうしないと表示されない場合があります。また、複数のファイルをダウンロードするためにソリューションを適応させる必要があります。

2
Melanie

@Dmitry Noginの答えを改善するために:これは私の場合うまくいきました。

ただし、さまざまなOS /ブラウザの組み合わせでファイルダイアログがどのように機能するのかわからないため、テストされていません。 (このようにコミュニティ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>
1
Karel Bílek

以下がその方法です。複数の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ルーチンへの基本的な呼び出しです(バニラのルール!)。 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;
      }
   }

秘Theは、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();
0
Peter
           <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>
0
user5598894

私はこれを行う解決策を探していますが、javascriptでファイルを解凍することは私が好きなほどきれいではありませんでした。ファイルを単一のSVGファイルにカプセル化することにしました。

サーバーにファイルを保存している場合(そうではありません)、SVGでhrefを設定するだけです。

私の場合、ファイルをbase64に変換し、SVGに埋め込みます。

編集:SVGは非常にうまく機能しました。ファイルのみをダウンロードする場合は、Zipの方が適している場合があります。ファイルを表示する場合は、SVGが優れているようです。

0
VectorVortec

以下のコードは100%動作しています。

ステップ1:以下のコードを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);
                })
            })
        };
    });

NOTE:ダウンロードする3つのファイルすべてが、angularProject/index.htmlまたはangularProject/index.jsファイル。

0
solanki...

Ajax呼び出しでurlのリストを取得し、 jquery plugin を使用して複数のファイルを並行してダウンロードします。

  $.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
Ali

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

            });     
        }

ハッピーダウンロード!

0
stritzi

これはすべてのブラウザ(IE11、firefox、Edge、ChromeおよびChrome Mobile)で機能します。私のドキュメントは複数の選択要素にあります。ブラウザーは速すぎて実行しようとすると問題が発生するようです。そのため、タイムアウトを使用しました。

//user clicks a download button to download all selected documents
$('#downloadDocumentsButton').click(function () {
    var interval = 1000;
    //select elements have class name of "document"
    $('.document').each(function (index, element) {
        var doc = $(element).val();
        if (doc) {
            setTimeout(function () {
                window.location = doc;
            }, interval * (index + 1));
        }
    });
});

これはプロミスを使用するソリューションです:

 function downloadDocs(docs) {
        docs[0].then(function (result) {
            if (result.web) {
                window.open(result.doc);
            }
            else {
                window.location = result.doc;
            }
            if (docs.length > 1) {
                setTimeout(function () { return downloadDocs(docs.slice(1)); }, 2000);
            }
        });
    }

 $('#downloadDocumentsButton').click(function () {
        var files = [];
        $('.document').each(function (index, element) {
            var doc = $(element).val();
            var ext = doc.split('.')[doc.split('.').length - 1];

            if (doc && $.inArray(ext, docTypes) > -1) {
                files.unshift(Promise.resolve({ doc: doc, web: false }));
            }
            else if (doc && ($.inArray(ext, webTypes) > -1 || ext.includes('?'))) {
                files.Push(Promise.resolve({ doc: doc, web: true }));
            }
        });

        downloadDocs(files);
    });
0
Zach Painter