2016-10-17 9 views
0

ダウンロードしたファイル(私の.txtファイルの場合)をオンザフライで生成する最適な方法は何ですか?これは私が以前にサーバーにファイルを格納せずに意味します。理解のために、ここで私を成し遂げるために必要なものです:laravel5.3オンザフライでダウンロードファイル(.txt)を生成

public function getDesktopDownload(Request $request){ 

     $txt = "Logs "; 

     //offer the content of txt as a download (logs.txt) 
     $headers = ['Content-type' => 'text/plain', 'Content-Disposition' => sprintf('attachment; filename="test.txt"'), 'Content-Length' => sizeof($txt)]; 

     return Response::make($txt, 200, $headers); 
} 

答えて

1

てみなどのコンテンツのストリームを送信するコンテンツ

$logs = Log::all(); 

$txt = "Logs \n"; 


foreach ($logs as $log) { 
    $txt .= $logs->id; 
    $txt .= "\n"; 
} 

を準備し、その後、上部に上記のクラスを使用しますこの

public function getDownload(Request $request) { 
$logs = Log::all(); 
$txt = "Logs \n"; 


foreach ($logs as $log) { 
    $txt .= $logs->id; 
    $txt .= "\n"; 
} 

$myName = "logs.txt"; 

$headers = ['Content-type' => 'text/plain', 'Content-Disposition' => sprintf('attachment; filename="%s"', $myName), 'Content-Length' => sizeof($txt)]; 

return Response::make($txt, 200, $headers); 

}

+0

ファイルサイズがphpの許容メモリを超えると失敗します。したがって、phpが128MBのメモリを持ち、ファイルサイズが128 MBを超える場合、メモリに関する致命的なエラーが発生するため、代わりにストリームレスポンスで解決できます大きなファイルの問題。それはチャンクでファイルを送信します。以下の回答を確認してください。 –

+0

@Pratik Boda上記のコードを編集しました。問題は、ダウンロード用に取得したファイルで、文字「L」が含まれています。どこがうまくいかないのか? – wichtel

+0

@wichtel foreachループを削除して、$ txt = "this is test"を追加してみてください。同じo/pを生成する –

2

あなたは、ダウンロードファイルなどのコンテンツを送信するために、ストリーム応答を使用することができます

(.txtファイルの私の場合は)、ダウンロードを生成するための最良の方法は何急いで?これは私が以前にサーバーにファイルを格納せずに意味します。理解のために、ここで私を成し遂げるために必要なものです:

use Symfony\Component\HttpFoundation\ResponseHeaderBag; 
use Symfony\Component\HttpFoundation\StreamedResponse; 

は、ダウンロード

$response = new StreamedResponse(); 
$response->setCallBack(function() use($txt) { 
     echo $txt; 
}); 
$disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'logs.txt'); 
$response->headers->set('Content-Disposition', $disposition); 

return $response;