【问题标题】:Save file from ajax从ajax保存文件
【发布时间】:2014-12-02 11:28:21
【问题描述】:

我想保存在服务器上生成的图像。为此,我使用 iframe,但单击后不会出现“文件保存”对话框。我做错了什么?

index.php

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
        <script>
            $(document).ready(function() {
                $('#onv-save-button').click( function() {
                    $.ajax ({               
                        url: "/ajax.php",
                        type: "POST",
                        success: function(data) {
                            $('#downloadFrame').attr('src' , data);
                        }
                    });
                });
            });

        </script>
    </head>
    <body>
        <iframe src="" id="downloadFrame" ></iframe>
        <button id="onv-save-button">Go!</button>
    </body>
</html>

ajax.php

<?  

    // Some actions to generate image
    echo "1.png" ;
?>

【问题讨论】:

  • >> echo "1.png" -- 你在你的 downloadFrame 元素中看到这个文本了吗?
  • 您知道您只是在浏览器输出中打印“1.png”吗?
  • 点击后我在downloadFrame中看到了我的图片。
  • 文件保存对话框的代码在哪里?您知道的唯一代码是,单击#onv-save-button 后,它将在 iframe 中回显1.png
  • 你能举一个这段代码的例子吗?

标签: php jquery ajax iframe download


【解决方案1】:

我做到了。这是问题的答案。

index.php

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
        <script>
            $(document).ready(function() {
                $('#onv-save-button').click( function() {
                    $.ajax ({               
                        url: "/ajax.php",
                        type: "POST",
                        success: function(data) {
                            alert(data);
                            $('#downloadFrame').attr('src' , "download.php?file=" + data);
                        }
                    });
                });
            });

        </script>
    </head>
    <body>
        <iframe src="" id="downloadFrame" ></iframe>
        <button id="onv-save-button">Go!</button>
    </body>
</html>

ajax.php

<?  
    echo $_SERVER["DOCUMENT_ROOT"]."/1.png";
?>

下载.php

<?php

    $content = file_get_contents($_REQUEST['file']);
    header('Content-Description: File Transfer');
    header("Cache-Control: ");
    header("Pragma: ");
    header("Content-Disposition: attachment; filename=\"".basename($_REQUEST['file'])."\"");

    ob_end_clean();
    ob_start();
    echo $content;
    ob_end_flush();
    exit();

?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多