Programming

한 번의 작업으로 여러 파일 다운로드

procodes 2020. 8. 18. 20:23
반응형

한 번의 작업으로 여러 파일 다운로드


표준 웹 기술을 사용하여 이것이 가능한지 확실하지 않습니다.

사용자가 한 번의 작업으로 여러 파일을 다운로드 할 수 있기를 바랍니다. 즉, 파일 옆의 확인란을 클릭 한 다음 확인 된 모든 파일을 가져옵니다.

가능합니까-그렇다면 어떤 기본 전략을 권장합니까? 나는 comets 기술을 사용하여 HttpResponse를 트리거하는 서버 측 이벤트를 만들 수 있다는 것을 알고 있지만 더 간단한 방법이 있기를 바랍니다.


HTTP는 한 번에 둘 이상의 파일 다운로드를 지원하지 않습니다.

두 가지 솔루션이 있습니다.

  • x 개의 창을 열어 파일 다운로드를 시작합니다 (JavaScript로 수행됨).
  • 선호하는 솔루션 파일을 압축하는 스크립트 생성

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>


숨겨진 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);
    });
  }

이 솔루션은 모든 브라우저에서 작동하며 경고를 트리거하지 않습니다. 을 만드는 대신 iframe여기에서 각 파일에 대한 링크를 만듭니다. 이렇게하면 경고 메시지가 표시되지 않습니다.

루핑 부분을 처리하기 위해 setTimeoutIE에서 작동하는 데 필요한를 사용합니다.

/**
 * 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>


가장 쉬운 방법은 ZIP 파일로 묶인 여러 파일을 제공하는 것입니다.

여러 개의 iframe 또는 팝업을 사용하여 여러 파일 다운로드를 시작할 수 있다고 가정하지만 사용성 관점에서 보면 ZIP 파일이 여전히 더 좋습니다. 누가 브라우저에 표시되는 10 개의 "다른 이름으로 저장"대화 상자를 클릭할까요?


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

각도 솔루션 :

HTML

    <!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


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

이 기술의 유일한 부작용은 사용자가 제출과 다운로드 대화 상자 사이에 지연이 표시된다는 것입니다. 이 효과를 최소화하려면 여기 와이 질문에 설명 된 기술을 사용하는 것이 좋습니다. 브라우저가 다운로드를 시작 했음을 알 수 있도록 파일과 함께 쿠키를 설정하는 파일 다운로드수신 할 때 검색합니다 . 이 쿠키를 클라이언트 측에서 확인하고 서버 측으로 보내야합니다. 쿠키에 적절한 경로를 설정하는 것을 잊지 마십시오. 그렇지 않으면 쿠키가 표시되지 않을 수 있습니다. 또한 여러 파일 다운로드를 위해 솔루션을 조정해야합니다.


@Dmitry Nogin의 답변을 개선하려면 내 경우에 효과가있었습니다.

그러나 다양한 OS / 브라우저 조합에서 파일 대화 상자가 어떻게 작동하는지 확실하지 않기 때문에 테스트되지 않았습니다. (따라서 커뮤니티 위키.)

<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>

           <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>

이 작업을 수행하는 솔루션을 찾고 있지만 자바 스크립트에서 파일 압축을 풀면 내가 좋아하는 것만 큼 깨끗하지 않았습니다. 파일을 단일 SVG 파일로 캡슐화하기로 결정했습니다.

서버에 파일이 저장되어 있다면 (저는 없습니다) SVG에서 href를 설정하기 만하면됩니다.

제 경우에는 파일을 base64로 변환하여 SVG에 포함하겠습니다.

편집 : SVG는 매우 잘 작동했습니다. 파일 만 다운로드하려는 경우 ZIP이 더 좋을 수 있습니다. 파일을 표시하려는 경우 SVG가 우수 해 보입니다.


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

            });     
        }

즐거운 다운로드 되세요!


아래 코드는 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);
                })
            })
        };
    });

참고 : 다운로드 할 세 파일이 모두 angularProject / index.html 또는 angularProject / index.js 파일 과 함께 동일한 폴더에 있는지 확인하십시오 .


이것은 모든 브라우저 (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));
        }
    });
});

이것은 promise를 사용하는 솔루션입니다.

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

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

    });

여기에 내가하는 방법이 있습니다. 여러 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;
      }
   }

트릭은 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();

지금까지 가장 쉬운 솔루션 (적어도 우분투 / 리눅스에서는) :

  • 다운로드 할 파일의 URL (예 : file.txt)로 텍스트 파일을 만듭니다.
  • 파일을 다운로드하려는 디렉토리에 'file.txt'를 넣으십시오.
  • 이전 라인의 다운로드 디렉토리에서 터미널을 엽니 다.
  • 'wget -i file.txt'명령을 사용하여 파일을 다운로드하십시오.

매력처럼 작동합니다.

참고 URL : https://stackoverflow.com/questions/2339440/download-multiple-files-with-a-single-action

반응형