通过PHP从Iframe下载文件时显示“另存为”对话框

时间:2012-09-26 06:46:07

标签: php jquery cross-domain download

我之前曾经问过类似的问题,但我相信这个问题有些不一致。

我的网页有Iframe。此iframe从其他某个域加载页面(跨域脚本正在运行)。现在,当我点击此iframe中的按钮时,它会通过AJAX发出jQuery请求,并在PHP服务器上创建一个文本文件。现在我希望出现一个正常的“另存为”对话框,以便我用户可以从服务器下载该文件。

我已经在PHP端尝试了所有Content-Dispositionheader()功能,但是虽然在服务器上成功创建了文件,但“另存为”对话框不会出现。我想,问题是我想从iframe触发文件下载,iframe正在从其他域加载内容。

有没有解决方法呢?

感谢。

1 个答案:

答案 0 :(得分:1)

我自己找到了解决方案。而不是AJAX使用Iframe技术。以下jQuery代码应写在iframe中。它通过iframe触发下载,而不是向服务器发出AJAX请求。

$(document).ready(function(){
    $('#download').click(function(){
        var ifr = $('<iframe id="secretIFrame" src="" style="display:none; visibility:hidden;"></iframe>');
        $('body').append(ifr);
        var iframeURL = 'http://you_domain.com/download.php?str='+encodeURIComponent(data_to_be_posted);
        ifr.attr('src', iframeURL);
        return false;
    });
});

这是download.php的代码:

<?php
$str = html_entity_decode($_REQUEST['str']);

$file_name = 'export_data.txt';

header("Cache-Control: ");// leave blank to avoid IE errors
header("Pragma: ");// leave blank to avoid IE errors
header("Content-Disposition: attachment; filename=\"".$file_name."\"");
header("Content-length:".(string)(filesize($str)));
header("Content-Type: application/force-download");
header("Content-Type: application/download");
header('Content-Type: application/octet-stream');
header('Content-Type: application/txt');
header("Content-Transfer-Encoding: binary ");
echo $str;
exit;
?>