Laravel:强制下载字符串而无需创建文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41425812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:02:31  来源:igfitidea点击:

Laravel : Force the download of a string without having to create a file

laravel

提问by Marc Brillault

I'm generating a CSV, and I want Laravel to force its download, but the documentationonly mentions I can download files that already exist on the server, and I want to do it without saving the data as a file.

我正在生成一个 CSV,我希望 Laravel 强制下载它,但文档只提到我可以下载服务器上已经存在的文件,我想在不将数据保存为文件的情况下进行下载。

I managed to make this (which works), but I wanted to know if there was another, neater way.

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

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

I also tried with a SplTempFileObject(), but I got the following error : The file "php://temp" does not exist

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

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

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

回答by Brian Dillingham

Make a response macrofor a cleaner content-disposition / laravel approach

为更清晰的内容处理/laravel 方法制作响应宏

Add the following to your App\Providers\AppServiceProviderboot method

将以下内容添加到您的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);

});

then in your controller or routes you can return the following

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

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

回答by omarjebari

A Laravel 7 approach would be (from the docs):

Laravel 7 方法将是(来自文档):

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

回答by Paulo Costa

Try this:

尝试这个:

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