2014-12-02 79 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(); 

?>