fix: 无法下载大文件

This commit is contained in:
kuaifan 2024-08-06 18:24:49 +08:00
parent f1ecf33ce7
commit e8af0f2ea6

View File

@ -2966,17 +2966,10 @@ class Base
*/ */
public static function streamDownload($file, $name = null) public static function streamDownload($file, $name = null)
{ {
$contentType = 'application/octet-stream';
if ($name && !str_contains($name, '.')) { if ($name && !str_contains($name, '.')) {
$name .= "."; $name .= ".";
} }
// //
if ($file instanceof \Closure) {
return Response::streamDownload($file, $name, [
'Content-Type' => $contentType,
]);
}
//
if (!$file instanceof File) { if (!$file instanceof File) {
if ($file instanceof \SplFileInfo) { if ($file instanceof \SplFileInfo) {
$file = new File($file->getPathname()); $file = new File($file->getPathname());
@ -2987,12 +2980,23 @@ class Base
if (!$file->isReadable()) { if (!$file->isReadable()) {
throw new FileException('File must be readable.'); throw new FileException('File must be readable.');
} }
$contentType = $file->getMimeType() ?: $contentType; // 大于100M直接下载
$content = $file->getContent(); if ($file->getSize() > 100 * 1024 * 1024) {
return Response::streamDownload(function() use ($content) { return Response::download($file->getPathname(), $name);
echo $content; }
}, $name, [ //
'Content-Type' => $contentType, $filePath = $file->getPathname();
return Response::stream(function () use ($filePath) {
$fileStream = fopen($filePath, 'r');
while (!feof($fileStream)) {
echo fread($fileStream, 1024);
flush();
}
fclose($fileStream);
}, 200, [
'Content-Type' => 'application/octet-stream',
'Content-Disposition' => 'attachment; filename="'.$name.'"',
'Content-Length' => $file->getSize(),
]); ]);
} }