2017-02-15 45 views
0

我試圖下載中心使用SlimPHP一個文件,它似乎並沒有爲我工作。SlimPHP應用不下載文件

這裏是我所做的路線:我知道一個事實,即$導出文件是一個有效的PHP流媒體資源作爲文件的內容回來的響應

$backendApp->post('/export', function ($request, $response, $args) { 
     $emails = $this->orginization->exportEmails(); 
     $exportFile = $this->file->writeEmailExport($emails, 'AllEmails.csv'); 

     $fh = fopen($exportFile, "r"); 
     $stream = new \Slim\Http\Stream($fh); 

     $response = $response->withHeader('Content-Type', 'application/octet-stream') 
      ->withHeader('Content-Description', 'File Transfer') 
      ->withHeader('Content-Disposition', 'attachment; filename="' . basename($exportFile) . '"') 
      ->withHeader('Content-Length', filesize($exportFile)) 
      ->withBody($stream); 

     return $response; 
    }); 

,我只需要觸發用戶的瀏覽器文件下載功能。

這些是出現在響應標題:

Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0 
Connection:close 
Content-Description:File Transfer 
Content-Disposition:attachment; filename="AllEmails.csv" 
Content-Length:267 
Content-Type:application/octet-stream 
Expires:Thu, 19 Nov 1981 08:52:00 GMT 
Host:localhost:8080 
Pragma:no-cache 
X-Powered-By:PHP/5.6.15 

做任何事情馬上傑出的事物,我做錯了什麼?我可以看到文件的內容返回到響應選項卡,因此我知道我正在獲取文件的內容,我只需要提示用戶下載該文件。

+0

我的下載文件的代碼不使用超薄框架和我的代碼是3+歲,所以也許我不應該評論,但我只是想知道 - 你試過用'的preg_replace(「([^ \ W \ S \ d \ -_〜,;:\ [\] \(\]] | [\] {2}。。。。)」, '',$導出文件)'和'filter_var($ dl_file,FILTER_SANITIZE_URL)'其中' $ dl_file'是preg_replace函數,以消除任何無效字符的結果嗎?如果你所得到的文件的內容....我不能完全肯定這會有所幫助,只是一個想法。 – Inkdot

回答

1

它涉及到,但是你在呼喚這是此代碼的工作:

$app = new \Slim\App($config); 

$app->get("/", function ($request, $response, $args) { 

    $response->write(
     <<<EOT 
<form method="POST" action="/export"> 
<input type="submit" value="Download"> 
</form> 
EOT 
    ); 

    return $response; 
}); 

$app->post('/export', function ($request, $response, $args) { 
    $exportFile = __DIR__ . '/../test_file.txt'; 

    $fh = fopen($exportFile, "r"); 
    $stream = new \Slim\Http\Stream($fh); 

    $response = $response->withHeader('Content-Type', 'application/octet-stream') 
     ->withHeader('Content-Description', 'File Transfer') 
     ->withHeader('Content-Disposition', 'attachment; filename="' . basename($exportFile) . '"') 
     ->withHeader('Content-Length', filesize($exportFile)) 
     ->withBody($stream); 

    return $response; 
}); 

你說,你可以看到在響應選項卡的信息。這是否意味着你通過JavaScript觸發了這個?如果是這樣,那麼瀏覽器會將文件發送回JS而不是發送給用戶。如果您希望文件下載對話框出現,請提供一個表單(如您想要的POST)並在其上放置一個按鈕以供用戶單擊。

+0

唉唉是您的有關調用的路線評論通過JavaScript是現貨,謝謝 – Xenology