加载另一个页面时下载文件

时间:2012-09-07 01:57:47

标签: php javascript joomla download

上下文是这样的:

  1. 用户点击按钮
  2. 页面上刷新了新页面信息(echo用于打印html代码)。
  3. 创建了一个file.txt
  4. 创建文件的下载应自动开始
  5. 使用下面的代码,将创建文件并显示页面的其余部分,但不会开始下载。此外,如果我点击链接,下载不会启动,但txt文件在浏览器中打开(我想强制下载)。

    另一方面,如果我评论javascript并取消注释标题指令,我刷新正确的页面并下载txt文件,但该文件的内容是错误的(它包含在其余部分中回显的html代码)页)。

    =================不工作代码==================

          echo "
          <form name=\"fn\" action=\"index.php?option=com_comp\" method=\"post\">
          // more not related stuff
          <input type=\"image\" src=\"".JURI::root().
          "components/com_comp/images/download_icon.png\" .
          "\" name=\"downloadaddresses\">DOWNLOAD_RESULTS
          // more not related stuff";
    
    
          if($_POST['downloadaddresses_x']!=0) {
    
                $myfilename = "tmp/results.txt";
                $fh = fopen($myfilename, 'w');
    
                $recipients = $_POST['recipients'];
                $semicolon_separated = implode(";", $recipients);
    
                fwrite($fh, $semicolon_separated);
                fclose($fh);
    
    
                /*header('Content-disposition: attachment; filename='.$myfilename);
                header("Content-type: application/octet-stream");*/
    
                echo "<a href=\"".$myfilename."\" id=\"downloadlink\">
                This download should start automatically!</a>";
                echo "<script type=\"text/javascript\">
                        newwindow=function{
                window.open('".$myfilename."','name','height=400,width=200');
                        if (window.focus) {newwindow.focus()}}
                    </script>";
            }           
    

    ========================更多不起作用的代码================= =

        <script type="text/javascipt">  
        var el = document.getElementById('downloadlink');
        if (document.createEvent) {
            var event = document.createEvent(\"MouseEvents\");
            event.initEvent(\"click\", true, true);
            el.dispatchEvent(event);
        }
        else if (el.click) {
            el.click();
        }
        </script>
    

1 个答案:

答案 0 :(得分:1)

而不是这个click模拟代码:

<script type="text/javascipt">  
var el = document.getElementById('downloadlink');
if (document.createEvent) {
    var event = document.createEvent(\"MouseEvents\");
    event.initEvent(\"click\", true, true);
    el.dispatchEvent(event);
}
else if (el.click) {
    el.click();
}
</script>

你能用这个:

<script type="text/javascript">
    location.href = document.getElementById('downloadlink').getAttribute('href');
</script>