2015-04-22 40 views
1

我使用圖像選擇器插件來選擇圖像,然後強制它下載。我努力編碼PHP,並按預期工作。下載彈出窗口,我設法查看文件。我不知道爲什麼它沒有在AJAX中工作。我錯過了什麼?強制使用ajax和php下載文件

//get the image-source or URL 
    function getImageSrc() 
    { 
     var req = $("div[class='thumbnail selected']").children('img'); 
      var imagessource = []; 
       $(req).each(function (datakey, datavalue) { 
           src = $(datavalue).attr('src'); 
             imagessource.push(src); 
               }); 
         return(imagessource); 
    } 

這裏是當我點擊按鈕

$("#download_media").click(function() { 
        var file = getImageSrc();  

        $.ajax({ 
         type: 'POST', 
         url: '?page=downloadController&action=downloadMedia', 
         data: {'file_url': file}, 
         success: function(data) { 
          console.log("success"); 
         } 
        }); 
       }); 

我的PHP文件

public function downloadMediaAction() 
{ 
    //get the file_url 
    $file = $this->getRequest()->('file_url'); 

    header("Content-Description: File Transfer"); 
    header("Content-Type: application/octet-stream"); 
    header('Content-Disposition: attachment; filename="'.basename($file).'"'); 
    readfile($file); 
} 
+2

你想瀏覽器顯示下載窗口等?然後只是重定向到該鏈接。 AJAX並不意味着這一點。 –

+0

當我嘗試window.location('你'),它只是顯示頁面。它沒有下載。 – asdasdas

+0

在發佈此問題之前,您是否嘗試過搜索?我在[Google](https://www.google.com.au/search?site=&source=hp&q=ajax+force+file+&hl=zh-TW)中花了15秒後發現了很多答案,下載和OQ = AJAX +力+文件+下載和gs_l = hp.3..0j0i22i30l2.142.4160.0.4325.27.17.1.0.0.1.623.2589.2-2j3j1j1.7.0.msedr ... 0 ... 1c.1.64.hp .. 20.7.2201.0.WdAWKKEFaK0):http://stackoverflow.com/questions/3502267/download-a-file-using-ajax –

回答

0

好,然後從你的AJAX請求,返回文檔的URL下載,如:

{'url':'http://server:port/path/to/file.php?id=x'}

,然後使用JavaScript

document.location='http://server:port/path/to/file.php?id=x';

在file.php打電話給你的方法:public function downloadMediaAction()

,並確保瀏覽器會下載它此行添加到downloadMediaAction()

header("Content-Type: application/force-download");

+0

他使用ajax發出請求,所以不行,添加頭文件**將不起作用。 –

+0

關於內容類型說謊是個壞主意。 –

+0

它曾經爲我在所有主流瀏覽器中工作 –