浏览器不提示下载文件-Laravel 6

时间:2019-11-14 17:37:18

标签: php laravel csv axios

[已解决]必须将download()方法拆分为2,所以它先生成generateCSV(),然后再获取getDownload()。

生成文件后,将其添加到sweetalert确认按钮上,该路由指向getDownload()。

preConfirm: () => {
    window.location.href = "/customers/resale/filterToCSV/download";
}

用户选中几个复选框以过滤数据库表后,服务器将写入CSV文件,但不会提示浏览器下载它。

路线:

Route::get('/customers/resale/filterToCSV', 'Resale_customerController@getFilteredQueryResults');

刀片视图:

axios.get('/customers/resale/filterToCSV', {
    params: {
        dataFromClient: arrJson,
    }
})
.then(function (response) {
    Swal.fire({
        icon: 'success',
        title: '...',
        text: '...',
    })
    console.log("Response (Filtered data to CSV): " + response.data);
});

控制器:

public function getFilteredQueryResults(Request $request)
{
    $arr = json_decode($request->dataFromClient, true);

    $selection = $this->queryBuilderFromCheckboxSelection($arr);
    $jsn = $selection->toJson();

    $this->download($jsn);

}

调用download()方法:

public function download($jsn)
{
    $filePath = public_path().'\\file.csv';

    $headers = array(
        "Content-type" => "text/csv",
        "Content-Disposition" => "attachment; filename=file.csv",
        "Pragma" => "no-cache",
        "Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
        "Expires" => "0"
    );

    $jsonDecoded = json_decode($jsn, true);

    $csvFileName = 'file.csv';

    $fp = fopen($csvFileName, 'w');

    foreach ($jsonDecoded as $row) {
        fputcsv($fp, $row);
    }

    fclose($fp);

    echo response()->download($filePath, $csvFileName, $headers);
    return response()->download($filePath, $csvFileName, $headers);//->deleteFileAfterSend(true);

}

知道我想念什么吗?谢谢!

0 个答案:

没有答案