2014-12-02 61 views
-1

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

的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" ; 
?> 
+0

>>回声 “1.png” - 你看到这段文字的downloadFrame元素? – 2014-12-02 11:31:45

+0

你知道你只是在浏览器输出中打印“1.png”吗? – 2014-12-02 11:32:51

+0

点击后,我会在downloadFrame中看到我的图片。 – JeiKei 2014-12-02 11:41:22

回答

0

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

的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"; 
?> 

的download.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(); 

?>