Reputation: 191
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
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
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
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