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

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

最佳答案

试试这个

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

关于php - laravel5.3 即时生成下载(.txt),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40084474/

相关文章:

php - 如何在 Apache 上修改代理图像 header ?

c++ - OpenGL header 中的平台特定宏

PHP 和 MYSQL : Why does A work and B not work?

javascript - 我如何更改 woocommerce 中产品默认下拉排序的样式

javascript - HTML anchor 标记无法在 Android 平台中下载文件

node.js - 使用 SAS (NODEJS) 从 Azure Blob 存储创建可共享 URI

php - 检查 2 个数组是否至少有 1 个相等的值

PHP MySQL 下拉列表搜索

java - 错误时自动恢复的 HTTP 异步下载器

c - 第一次在 c 中使用 headers 并且真的不太了解它