Javascript使用iframe下载多个文件

时间:2014-01-14 12:44:01

标签: javascript iframe

我需要用一个按钮下载多个文件“全部下载”,我不想压缩它们,我想用javascript和隐藏的iframe下载它们,我怎么能这样做?这里是iframe和javascript的例子,但是我不明白我需要发送什么url到ifrm.setAttribute(“src”,url);什么是'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 );
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您需要将直接文件URL(或导致直接下载的URL)传递到iframe src。在您的脚本案例中, somefile.do 可能是一些下载处理程序,文件ID和操作由它的参数传递。

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

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

您必须将其作为参数传递给makeFrame函数:

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

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

答案 1 :(得分: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();
});

你做好了准备:)