Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel:强制下载字符串而不必创建文件_Laravel - Fatal编程技术网

Laravel:强制下载字符串而不必创建文件

Laravel:强制下载字符串而不必创建文件,laravel,Laravel,我正在生成一个CSV,我希望Laravel强制下载,但只提到我可以下载服务器上已经存在的文件,我希望这样做而不将数据保存为文件 我设法做到了这一点(这是可行的),但我想知道是否还有其他更整洁的方法 $headers = [ 'Content-type' => 'text/csv', 'Content-Disposition' => 'attachment; filename="download.csv"', ];

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

我设法做到了这一点(这是可行的),但我想知道是否还有其他更整洁的方法

    $headers = [
        'Content-type'        => 'text/csv',
        'Content-Disposition' => 'attachment; filename="download.csv"',
    ];
    return \Response::make($content, 200, $headers);
我还尝试了使用,但出现以下错误:
文件“php://temp“不存在

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

    return response()->download($tmpFile);
试试这个:

// 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);
制定一个更清晰的内容处理/laravel方法

将以下内容添加到
App\Providers\AppServiceProvider
boot方法

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

Laravel 7的方法是(从以下方面):


对不起,我想要一种不会强迫我事先保存文件的方法。内容处理方法是最干净的方法谢谢!我真的很想知道没有任何内置函数的原因。^它可以工作,我添加了一个
$fileName
变量,以便动态设置文件名和扩展名。感谢您提供了一个雄辩的解决方案。我们可以像这样动态发送文件名:return response()->附件($csv,$filename);函数中的如下内容:\Response::macro('attachment',function($content,$fileName){$headers=['content type'=>'text/csv','content Disposition'=>'attachment;fileName='.$fileName,];return\Response::make($content,200,$headers); });
$contents = 'Get the contents from somewhere';
$filename = 'test.txt';
return response()->streamDownload(function () use ($contents) {
    echo $contents;
}, $filename);