Search code examples
phpdownloadheaderlaravel-5.3on-the-fly

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


What's the best way to generate a download (in my case of a .txt file) on the fly? By this I mean without storing the file on the server before. For understanding here's what I need to get done:

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);
}

Solution

  • Try this

    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);
    }