wichtel
wichtel

Reputation: 191

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

Upvotes: 4

Views: 11348

Answers (3)

thirumal mani L
thirumal mani L

Reputation: 172

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

Upvotes: 1

Pratik Boda
Pratik Boda

Reputation: 414

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

Upvotes: 8

Sagar Rabadiya
Sagar Rabadiya

Reputation: 4321

you can use stream response to send content as download file

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:

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

use the above classes at top, then prepare content

$logs = Log::all();

$txt = "Logs \n";


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

then send a stream of content as download

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

Upvotes: 6

Related Questions