0

I need to download multiple files with one button "download all",I don't want to zip them, i want to download them with javascript and hidden iframe,how I can do it? here is the example with iframe and javascript ,but I don't understand what url I need to send to ifrm.setAttribute( "src", url ) ;What is 'somefile.do'?

function makeFrame( url ) 
{ 
    ifrm = document.createElement( "IFRAME" ); 
    ifrm.setAttribute( "style", "display:none;" ) ;
    ifrm.setAttribute( "src", url ) ; 
    ifrm.style.width = 0+"px"; 
    ifrm.style.height = 0+"px"; 
    document.body.appendChild( ifrm ) ; 
}  

function downloadChecked( )
{
    for( i = 0 ; i < document.downloadform.elements.length ; i++ )
    {
        foo = document.downloadform.elements[ i ] ;
        if( foo.type == "checkbox" && foo.checked == true )
        {
            makeFrame('somefile.do?command=download&fileid=' + foo.name );
        }
    }
}
James
  • 2,195
  • 1
  • 19
  • 22
user1059769
  • 43
  • 2
  • 10
  • 1
    You'll need to open as many iframes as files you have and the user will need to confirm them one by one. Is that the intended flow? – Álvaro González Jan 14 '14 at 12:50
  • Yes,and there are files from many types .xls,xml,doc.Is it possible?I am just new in javascript.. – user1059769 Jan 14 '14 at 12:53
  • Yes, but if you will have, for example, some plugin in browser to display those files directly, not download them, nothing happen. In that case, you should make some handler.php, which will send all files as attachements and will accept file names as in your example. – Pavel Štěrba Jan 14 '14 at 13:02

2 Answers2

1

You need to pass direct file URL (or URL which cause direct downloading) into iframe src. In your script case, somefile.do is probably some download handler and file ID and action is passed by it's parameters.

But back to your question, if you have files:

  • example.com/file1.zip
  • example.com/file2.zip
  • example.com/file3.zip

You have to pass it just into makeFrame function as a parameter:

makeFrame('http://example.com/file1.zip');

It will create iframe for every URL and start downloading (or display save dialog - depends on browser). Make sure to have files URLs in array and pass them in for loop.

Pavel Štěrba
  • 2,822
  • 2
  • 28
  • 50
1

I would recommend the multiDownload jQuery plugin. It's also using iframes, and keeps your code tidy.

Example:

<a href="document1.zip" class="document">document 1</a>
<a href="document2.zip" class="document">document 2</a>
<a href="document3.zip" class="document">document 3</a>

<a href="#" id="download_all">download all</a>

$('#download_all').click(function (event) {
    event.preventDefault();
    $('.document').multiDownload();
});

And you're ready :)

Marcell Kiss
  • 538
  • 3
  • 11