2016-06-10 86 views
1

我得到了一個CSV下載混亂。我很高興將它保存到一個文件並提供一個鏈接給用戶,但這似乎是從事情的錯誤判斷liketheseLaravel 5.2流下載

來自這個答案Use Laravel to Download table as CSV我想我發現stream()方法不再存在。

public function download() 
{ 
    $headers = [ 
      'Cache-Control'  => 'must-revalidate, post-check=0, pre-check=0' 
     , 'Content-type'  => 'text/csv' 
     , 'Content-Disposition' => 'attachment; filename=galleries.csv' 
     , 'Expires'    => '0' 
     , 'Pragma'    => 'public' 
    ]; 

    $list = $this->users->getAllUsers()->toArray(); 

    # add headers for each column in the CSV download 
    array_unshift($list, array_keys($list[0])); 

    $callback = function() use ($list) 
    { 
     $FH = fopen('php://output', 'w'); 
     foreach ($list as $row) { 
      fputcsv($FH, $row); 
     } 
     fclose($FH); 
    }; 

    // return Response::stream($callback, 200, $headers); // Old version 
    return response()->download($callback, 'Users-' . date('d-m-Y'), $headers); 

} 

我試圖使用Laravel 5.2 response()功能,但我剛開始有點失落,什麼我與響應 - download()看來合理的選擇,但是這給了我下面的錯誤:

Object of class Closure could not be converted to string

這是有道理的。什麼是正確的方式去做這件事?或者我應該保存文件,然後使用文件路徑作爲我的download()函數的第一個參數 - 這似乎是不好的做法?

回答

0

這是非常簡單和偉大的工作,一旦我取代了階級&靜態調用Response::有了助手功能,response()->

return response()->stream($callback, 200, $headers); 

我相信這使用StreamedResponse類。