doutao6380 2015-06-30 14:11
浏览 98
已采纳

使用AJAX $ .post后下载(强制另存为对话框)

I have a webapp that simulates a terminal. Every command is posted via AJAX using the following script (portion):

AJAX/jQuery

$.post("sec/cmd_process.php", { n : n } )
    .done(function(data){
        output.append(display(data));
    });

If the user types download log into the terminal, the following script - on sec/cmd_process.php is executed:

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

What I want to happen is for the generated file, log.txt, is downloaded via the Save As... dialog. This code works if you directly visit a PHP page with those headers, but how can I make it work through jQuery/AJAX?

  • 写回答

1条回答 默认 最新

  • douyi6818 2015-07-01 07:34
    关注

    The simplest solution I found was to return a <script> tag forwarding the location to a forced download page:

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

    sec/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);
    

    sec/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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)