Отдача большого файла по кусочкам Laravel
К примеру в роуте (/routes/web.php):
// ...
Route::get('get_file', 'App\Http\Controllers\TestController@get_file');
// ...
В контроллере (/app/Http/Controllers/TestController.php):
<?php
namespace App\Http\Controllers;
// ...
use App\Models\File;
use Symfony\Component\HttpFoundation\StreamedResponse;
class TestController extends Controllers
{
// ...
public function get_file(Request $request)
{
// ...
$get_file = File::where('id', $request->file_id)
->select('path', 'extension', 'basename')
->get();
$path = base_path() . '/files/' . $get_file[0]['path'];
$response = new StreamedResponse(function() use ($path) {
if ($file = fopen($path, 'rb')) {
while (!feof($file) and (connection_status()==0)) {
print fread($file, 1024*8);
flush();
}
fclose($file);
}
}, 200, [
'Content-Description' => 'File Transfer',
'Content-Type' => 'audio/' . $get_file[0]['extension'],
'Content-Disposition' => 'attachment; filename="' . $get_file[0]['basename'] . '"',
]);
return $response;
}
// ...
}