2014-01-14 163 views
0

我需要下载多个文件,只需一个按钮“下载全部”,我不想压缩它们,我想用javascript和隐藏的iframe下载它们,我该怎么做呢?这里是iframe和javascript的例子,但我不明白我需要发送到ifrm.setAttribute(“src”,url)什么网址;什么是'somefile.do'?Javascript下载多个iframe文件

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

你需要打开多个I帧,你有文件,用户需要确认他们一个接一个。这是预期的流量? –

+0

是的,并且有许多类型的文件.xls,xml,doc.Is它可能吗?我只是在JavaScript中新的.. – user1059769

+0

是的,但如果你将有,例如,浏览器中的一些插件直接显示这些文件,不下载它们,没有任何事情发生。在这种情况下,你应该制作一些handler.php,它将发送所有文件作为附件,并接受文件名,如你的例子。 –

回答

1

您需要通过直接的文件URL(或URL造成直接下载)到IFRAME SRC。在你的脚本案例中,somefile.do可能是一些下载处理程序和文件标识,并通过它的参数传递操作。

但是,回到你的问题,如果你有文件:

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

你必须将它传递刚刚进makeFrame功能参数:

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

它将为每个URL创建iframe并开始下载(或显示保存对话框 - 取决于浏览器)。确保在数组中有文件URL并将它们传递给for循环。

1

我会推荐multiDownload jQuery插件。它也使用iframe,并保持您的代码整洁。

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

,你准备好:)