laravel5.3动态生成下载(.txt)

时间:2016-10-17 10:50:49

标签: php download header laravel-5.3 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);
}

3 个答案:

答案 0 :(得分:4)

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

在运行中生成下载(在我的.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;

答案 1 :(得分:4)

试试这个

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

答案 2 :(得分:0)

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