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

wic*_*tel 2 php header download on-the-fly laravel-5.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);
}
Run Code Online (Sandbox Code Playgroud)

小智 6

尝试这个

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);
}
Run Code Online (Sandbox Code Playgroud)


小智 5

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

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

use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\StreamedResponse;
Run Code Online (Sandbox Code Playgroud)

首先使用上述类,然后准备内容

$logs = Log::all();

$txt = "Logs \n";


foreach ($logs as $log) {
    $txt .= $logs->id;
    $txt .= "\n";
}
Run Code Online (Sandbox Code Playgroud)

然后发送内容流作为下载

$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;
Run Code Online (Sandbox Code Playgroud)