【问题标题】:Show 'Save as' dialog box while downloading file from an Iframe through PHP通过 PHP 从 Iframe 下载文件时显示“另存为”对话框
【发布时间】:2012-09-26 06:46:07
【问题描述】:

我知道以前有人问过类似类型的问题,但我相信这个问题有些不同。

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

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

有什么解决方法吗?

谢谢。

【问题讨论】:

    标签: php jquery cross-domain download


    【解决方案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;
    ?>
    

    【讨论】:

      猜你喜欢
      • 2021-08-20
      • 2015-03-28
      • 1970-01-01
      • 1970-01-01
      • 2018-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-03
      相关资源
      最近更新 更多