spatie / laravel-medialibrary

Associate files with Eloquent models
https://spatie.be/docs/laravel-medialibrary
MIT License
5.78k stars 1.08k forks source link

When streaming media, replace with feof/fread instead of fpassthru #3501

Closed chrispage1 closed 10 months ago

chrispage1 commented 10 months ago

Hi,

I ran into an issue where when returning a Media item directly in our controller, it was building our response as a stream but hitting memory allocation errors.

The reason for this is the functionality of fpassthru. It's designed to 'Output all remaining data on a file pointer' - https://www.php.net/manual/en/function.fpassthru.php

This update uses feof/fread to instead chunk the output and clear the buffers, preventing memory issues.

I've also added a setter to allow modification of the chunk size. Example usage:

public function show(Media $media) {
    // stream our media out in 5MB chunks
    return $media->setStreamChunkSize((1024*1024)*5);
}

While I was in the project I've also added a helper method to get a stream for a conversion, this was something that we've been using in a project of ours.

freekmurze commented 10 months ago

Thanks!