2015-06-30 52 views
0

我有一个webapp模拟终端。上sec/cmd_process.php执行 - 如果用户键入download log到终端,下面的脚本

AJAX/jQuery的

​​

使用下面的脚本(部)的每一个命令经由AJAX张贴

PHP

if(isset($_POST['n'])){ 

    echo $_POST['n']; 
    $t = explode(' ', $_POST['n']); 

    if(strtolower($t[0])=='download'){ 
     if(!isset($t[1])) shout_error("No download specified"); 

     //Download Log 
     elseif($t[1]=='log'){ 
      $stmt = $dbh->prepare("SELECT * FROM `tap_log` ORDER BY `time`"); 
      $stmt->execute(); 
      $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); 
      foreach($rows as $row) { 
       $user = user_by_id($row['user']); 
       $data.= "{$row['time']} - User {$user['id']} ({$user['name1']} {$user['name2']}) - {$row['information']} ({$row['subject']})".PHP_EOL; 
      } 

      $handle = fopen('log.txt','w+'); 
      fwrite($handle, $data); 
       $path = 'log.txt'; 
       header('Content-Transfer-Encoding: binary'); 
       header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($path)).' GMT'); 
       header('Accept-Ranges: bytes'); 
       header('Content-Length:'.filesize($path)); 
       header('Content-Encoding: none'); 
       header('Content-Disposition: attachment; filename='.$path); 
       readfile($path); 
      fclose($handle); 
     } 
    } 
} 

我想要发生的是通过“另存为...”对话框下载生成的文件log.txt。如果您直接访问带有这些标头的PHP页面,此代码可行,但是如何通过jQuery/AJAX使其工作?

+0

强制下载不可能通过ajax,AFAIK – Varun

+0

有没有其他的选择? – Ben

+0

无论是直接重定向到PHP,还是一个厚脸皮的解决方案,都会创建一个隐藏的'',其中href将用户重定向到PHP页面,并且您可以强制下载。 – Varun

回答

0

,我发现最简单的解决办法是返回一个<script>标签转发的位置,以强制下载页面:

<script type='text/javascript'> 
    location.href='sec/download.php?file=log.txt&type=text'; 
</script> 

秒/ cmd_process.php

$handle = fopen('log_'.time().'.txt','w+'); 
fwrite($handle, $data); 
    echo "Please wait while the file downloads..."; 
    echo "<script type='text/javascript'>location.href='sec/download.php?file=log.txt&type=text';</script>"; 
fclose($handle); 

秒/download.php

<?php 
    $filename = $_GET['file']; 
    $filetype = $_GET['type']; 
    header("Content-Transfer-Encoding: binary"); 
    header("Last-Modified: ".gmdate('D, d M Y H:i:s',filemtime($filename))." GMT"); 
    header("Accept-Ranges: bytes"); 
    header("Content-Length: ".filesize($filename)); 
    header("Content-Encoding: none"); 
    header("Content-Type: application/$filetype"); 
    header("Content-Disposition: attachment; filename=$filename"); 
    readfile($filename); 
相关问题