【问题标题】:Laravel 5.8 StreamDownload File Attachment Redirecting Instead of DownloadingLaravel 5.8 StreamDownload 文件附件重定向而不是下载
【发布时间】:2020-08-11 23:52:40
【问题描述】:

我认为我犯了一个在我的 Laravel 控制器中没有看到的错误。我有 JSON 数据,我想将其转换为 CSV,然后在浏览器中下载该文件。

我正在提交一个带有隐藏输入的表单,将 POST 数据发送到服务器,运行数据查询,然后使用 fputcsv() 创建文件流回调,并返回 Laravel 流响应。

我想流式下载它,而不是在服务器上写一个文件来下载。我知道使用 ajax 或 blob 来执行此操作的技巧,但我觉得下载 CSV 文件的表单 POST 应该非常简单,而且我正在做一些愚蠢的事情。如果我只返回原始数据,CSV 字符串看起来是正确的,所以我认为这不是处理或数据本身的问题。

导出控制器

protected function csvFileHeaders($filename) {
    return array(
        "Content-type" => "text/csv",
        "Content-Disposition" => "attachment; filename=". $filename,
        "Pragma" => "no-cache",
        "Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
        "Expires" => "0"
    );
}

public function __invoke() {

$filename = 'report_'.$endpoint.'_'.date('d-m-Y-H:i:s').'.csv';
$headers = $this->csvFileHeaders($filename);

$data    = $rows->toArray();
$columns = collect(request()->input('params.columns'))->map(function($c) {
    return $c['label'];
})->toArray();
$fields = collect(request()->input('params.columns'))->map(function($c) {
    return $c['value'];
})->toArray();

$callback = function() use ($data, $fields, $columns) {
    $file = fopen('php://output', 'rw');
    fputcsv($file, $columns);

    foreach($data as $d) {
        // MAP values to columns OR empty strings if value is not present
        fputcsv($file, collect($fields)->map(function($f) use ($d) {
            if ( array_key_exists($f, $d) ) { return $d[$f]; }
            return '';
        })->toArray());
    }

    fclose($file);
};


return response()->stream($callback, $filename, $headers);

}

前端 React POST 表单

<form id="report-export-form" action={'/report/export'} method="POST">
    <div dangerouslySetInnerHTML={{ __html: csrf_token }} />
    {/* BECOMES */}
    {/* <div><input type="hidden" name="_token" value="...token value..."></div> */}

    <input type="hidden" name="mode" value={form.mode)} />
    <input type="hidden" name="endpoint" value={endpoint} />

    <button className="btn btn-success" type="submit">
        Export to CSV
    </button>
</form>

页面重定向(刷新到原始页面)而不是文件下载,但没有下载文件。有谁知道我犯了什么错误?

【问题讨论】:

    标签: php download export-to-csv laravel-5.8 responsestream


    【解决方案1】:

    原来有一个验证器规则检查静默失败,导致重定向。

    修复验证并确保设置 Content-Type 和 Content-Disposition 标头已成功下载附件。

    故事的寓意--首先简单,不要剥夺自己的睡眠。

    【讨论】:

      猜你喜欢
      • 2021-10-26
      • 2020-05-27
      • 2014-04-29
      • 1970-01-01
      • 2019-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多