繁体   English   中英

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

[英]Show 'Save as' dialog box while downloading file from an Iframe through PHP

我知道以前曾问过类似类型的问题,但我相信这一问题有所不同。

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

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

有什么解决方法吗?

谢谢。

我自己找到了解决方案。 代替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;
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM