【问题标题】:Laravel : Force the download of a string without having to create a fileLaravel:强制下载字符串而无需创建文件
【发布时间】:2017-01-02 11:17:02
【问题描述】:

我正在生成一个 CSV,我希望 Laravel 强制下载它,但 the documentation 只提到我可以下载服务器上已经存在的文件,并且我想这样做而不将数据保存为文件。

我设法做到了(可行),但我想知道是否有另一种更简洁的方法。

    $headers = [
        'Content-type'        => 'text/csv',
        'Content-Disposition' => 'attachment; filename="download.csv"',
    ];
    return \Response::make($content, 200, $headers);

我也尝试使用SplTempFileObject(),但出现以下错误:The file "php://temp" does not exist

    $tmpFile = new \SplTempFileObject();
    $tmpFile->fwrite($content);

    return response()->download($tmpFile);

【问题讨论】:

    标签: laravel


    【解决方案1】:

    创建一个response macro 以获得更清晰的内容处置/laravel 方法

    将以下内容添加到您的 App\Providers\AppServiceProvider 引导方法中

    \Response::macro('attachment', function ($content) {
    
        $headers = [
            'Content-type'        => 'text/csv',
            'Content-Disposition' => 'attachment; filename="download.csv"',
        ];
    
        return \Response::make($content, 200, $headers);
    
    });
    

    然后在您的控制器或路由中,您可以返回以下内容

    return response()->attachment($content);
    

    【讨论】:

    • 我们可以像这样动态发送文件名:return response()->attachment($csv, $fileName);并且在函数中将是这样的: \Response::macro('attachment', function ($content, $fileName) { $headers = [ 'Content-type' => 'text/csv', 'Content-Disposition' => '附件; 文件名='.$fileName, ]; return \Response::make($content, 200, $headers); });
    【解决方案2】:

    Laravel 7 方法是(来自docs):

    $contents = 'Get the contents from somewhere';
    $filename = 'test.txt';
    return response()->streamDownload(function () use ($contents) {
        echo $contents;
    }, $filename);
    

    【讨论】:

      【解决方案3】:

      试试这个:

      // Directory file csv, You can use "public_path()" if the file is in the public folder
      $file= public_path(). "/download.csv";
      $headers = ['Content-Type: text/csv'];
      
       //L4
      return Response::download($file, 'filename.csv', $headers);
      //L5 or Higher
      return response()->download($file, 'filename.csv', $headers);
      

      【讨论】:

      • 抱歉,我想要一种不会强迫我事先保存文件的方法。
      猜你喜欢
      • 2021-07-31
      • 1970-01-01
      • 1970-01-01
      • 2014-11-14
      • 1970-01-01
      • 1970-01-01
      • 2014-03-23
      相关资源
      最近更新 更多