2017-01-02 59 views
12

我生成一個CSV文件,並且我希望Laravel強制其下載,但the documentation只提及我可以下載服務器上已有的文件,而我希望在不將數據保存爲文件的情況下執行此操作。Laravel:強制下載字符串而不必創建文件

我設法做出了這個(工作),但我想知道是否有另一個更乾淨的方式。

$headers = [ 
     'Content-type'  => 'text/csv', 
     'Content-Disposition' => 'attachment; filename="download.csv"', 
    ]; 
    return \Response::make($content, 200, $headers); 

我也試圖與一個SplTempFileObject(),但我得到了以下錯誤:The file "php://temp" does not exist

$tmpFile = new \SplTempFileObject(); 
    $tmpFile->fwrite($content); 

    return response()->download($tmpFile); 
+1

內容部署方法是最乾淨的方式 –

+0

謝謝!我真的很想知道爲什麼沒有任何內置函數的原因。 –

回答

18

使一個清潔的內容處置/ laravel一個response macro方法

將以下內容添加到您的App\Providers\AppServiceProvider引導方法

\Response::macro('attachment', function ($content) { 

    $headers = [ 
     'Content-type'  => 'text/csv', 
     'Content-Disposition' => 'attachment; filename="download.csv"', 
    ]; 

    return \Response::make($content, 200, $headers); 

}); 

然後在您的控制器或路線,你可以返回以下

return response()->attachment($content); 
-2

試試這個:

// Directory file csv, You can use "public_path()" if the file is in the public folder 
$file= public_path(). "/download.csv"; 
$headers = ['Content-Type: text/csv']; 

//L4 
return Response::download($file, 'filename.csv', $headers); 
//L5 or Higher 
return response()->download($file, 'filename.csv', $headers); 
+0

對不起,但我想要一種方法,不會強迫我事先保存文件。 –