Laravel 8中下载文件遭遇FileNotFoundException问题求助
Laravel 文件下载 FileNotFoundException 问题排查方案
问题重现
已将test.png放置在storage/app/public/test.png路径,使用以下代码尝试下载时触发FileNotFoundException,提示文件未在var/www/html/lav_8_filedownload/storage/app/public/test.png找到:
<a href="{{ route('export.download_response') }}"> <button>Export(Response)</button> </a>
class ExportController extends Controller { public function download_response(){ $filePath = Storage::path('public/test.png'); $fileName = 'test.png'; $mimeType = Storage::mimeType($filePath); $headers = [['Content-Type' => $mimeType]]; return response()->download($filePath, $fileName, $headers); } } Route::get('/export/download_response', [ExportController::class, 'download_response'])->name('export.download_response');
排查与解决步骤
1. 验证文件存在性与权限
- 直接登录服务器,检查
var/www/html/lav_8_filedownload/storage/app/public/test.png是否真实存在,Linux系统区分文件名大小写,确认文件名拼写完全一致 - 给storage目录设置正确权限,确保Web服务器用户(如
www-data)拥有读取权限:chmod -R 755 /var/www/html/lav_8_filedownload/storage/ chown -R www-data:www-data /var/www/html/lav_8_filedownload/storage/
2. 修正文件路径获取方式
尝试直接使用storage_path()函数获取绝对路径,替代Storage::path():
$filePath = storage_path('app/public/test.png');
或者先通过Storage::exists()验证文件是否可被Laravel的存储系统识别:
if (!Storage::exists('public/test.png')) { abort(404, '目标文件不存在'); } $filePath = Storage::path('public/test.png');
3. 修正请求头格式
当前代码中$headers是二维数组,不符合response()->download()的参数要求,改为一维数组:
$headers = ['Content-Type' => $mimeType];
4. 确认文件系统配置
检查config/filesystems.php中public磁盘的配置是否正确,默认配置应为:
'public' => [ 'driver' => 'local', 'root' => storage_path('app/public'), 'url' => env('APP_URL').'/storage', 'visibility' => 'public', ],
内容的提问来源于stack exchange,提问作者rorona
相关产品推荐
相关产品推荐

