laravel5.3 即时生成下载 (.txt)

laravel5.3 generate download (.txt) on the fly

即时生成下载(在我的情况下是 .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);
}

您可以使用流响应将内容作为下载文件发送

即时生成下载(在我的情况下是 .txt 文件)的最佳方法是什么?我的意思是之前没有将文件存储在服务器上。为了理解这里是我需要完成的事情:

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

在顶部使用上面的类,然后准备内容

$logs = Log::all();

$txt = "Logs \n";


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

然后发送内容流作为下载

$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;

试试这个

public function getDownload(Request $request) {
    // prepare content
    $logs = Log::all();
    $content = "Logs \n";
    foreach ($logs as $log) {
      $content .= $logs->id;
      $content .= "\n";
    }

    // file name that will be used in the download
    $fileName = "logs.txt";

    // use headers in order to generate the download
    $headers = [
      'Content-type' => 'text/plain', 
      'Content-Disposition' => sprintf('attachment; filename="%s"', $fileName),
      'Content-Length' => sizeof($content)
    ];

    // make a response, with the content, a 200 response code and the headers
    return Response::make($content, 200, $headers);
}
$images = DB::table('images')->get();
$content = "Names \n";
foreach ($images as $image) {
  $content .= $image->name;
  $content .= "\n";
}

$fileName = "logs.txt";

$headers = [
  'Content-type' => 'text/plain', 
  'Content-Disposition' => sprintf('attachment; filename="%s"', $fileName),
  'Content-Length' => strlen($content)
];   
return Response::make($content, 200, $headers);
use  strlen function in content-length if you use sizeof its always print one char in text document.