2017-06-07 55 views
1

我的目标是通过一次请求同时下载多个文件通过php。我无法使用'zip'解决方案压缩文件。所以我想出的解决方案是有一个空的iframe并动态更新源,以便iframe下载多个文件。Javascript更新iframe src通过循环下载多个文件

我有一个基本的页面与一个iframe,当用户点击他们下载的文件运行一个脚本循环通过选定的文件和更新的iframe源到PHP页面,这将下载一个文件:

网页,其中发送请求:

<script> 
function download_files(){ 
    // assume this is a loop which finds out all the files which were selected by the user 
    for (var i = 0, len = selected_fileids.length; i < len; i++) { 

     var fileid_single2 = selected_fileids[i].split("select_"); 
     fileid_splitted = fileid_single2[1]; 

     document.getElementById('iframe_downloader').src = "/index.php?page=download&fileid=" + id; 

    } 
} 
</script> 


<iframe src="" style="width:0;height:0;border:0; border:none;" id="iframe_downloader"></iframe>"; 

<!-- assume there will be checkboxes here which lets the user pick their files --> 

<p onclick="download_files();">download</p> 

PHP下载脚本,假设$文件路径和文件名$有正确的价值观:

header("Pragma: "); 
     header("Cache-Control: "); 
     header("Content-Type: application/force-download"); 
     header("Content-Disposition: attachment; filename=\"{$row_filename}.xls\""); 
     header("Content-Transfer-Encoding: binary"); 
     readfile($filepath); 

所以基本上,脚本循环遍历所有选定的文件,并不断更改源以尝试通过iframe下载所有文件。 我遇到的问题是,它似乎只实际下载最后一个文件..我已经尝试调试它,我可以看到它正在循环所有项目,因为我可以console.log该过程。然而,只有最后一个文件实际上是由iframe触发的。

我试过添加setInterval,那也不行。我看过提琴手,我可以确认只有最后一个文件被触发。

+0

你可以使用一个简单的元刷新到下一个php文件下载... – Sourcery

+0

@Sourcery如何在我的场景中工作?因为我无法进行页面刷新,哪里去? –

+0

也许我误解了你的代码,但是如果外部页面告知要下载哪个文件并在iframe(内部页面)中打开该文件,那么外部页面可以具有例如5秒的元刷新/重定向,重定向到新的调用iframe中下一个文件的页面... – Sourcery

回答

0

您可以为每次下载创建一个iframe。这是Javascript中的解决方案:

<script> 

function createFrame(url) { 
    var frame = document.createElement("iframe"); 
    frame.setAttribute("src",url); 
    frame.style.width = "0"; 
    frame.style.height = "0"; 
    frame.style.border = "none"; 
    document.body.appendChild(frame); 
} 

function download_files() { 
    var len = selected_fileids.length; 
    for (var i = 0; i < len; i++) { 
     var id = ....<incomplete original code>....; 
     createFrame("/index.php?page=download&fileid="+id); 
    } 
} 

</script> 

<a href="#" onclick="download_files();return false;">download</a> 

我必须警告,这段代码没有经过测试,它只是显示了这个想法。