Laravel 不强制下载文件

问题描述

我有一个功能,程序正在生成一个 .csv 文件,然后我想在浏览器中下载。问题是:调用函数时,文件显示在浏览器中,而不是下载它。有什么建议吗?

$csv=array($index,$value);
            
$filename='persons.xls';
$handle=fopen('persons.xls','w');
   
$headers = ['Content-Type: text/xls'];
foreach ($csv as $row) {
    fputcsv($handle,$row);
}
fclose($handle);
return Response::download(public_path('/persons.xls'),'persons.xls',$headers);

解决方法

使用此代码从 Laravel 下载 Microsoft Excel 文件:

$filename='persons.xls';
//---Get path from storage directory
//$path = storage_path('app/' . $filename);
//---Get the path from your public directory
$path = public_path('/persons.xls');

// Download file with custom headers
return response()->download($path,$filename,[
    'Content-Type' => 'application/vnd.ms-excel','Content-Disposition' => 'inline; filename="' . $filename . '"'
]);