Search code examples
phpsymfonyflysystem

BinaryFileResponse with php resource from Flysystem


I need to use BinaryFileResponse for correct handling of videos with Length Headers and co. Also I want the user to allow configured other storages (S3, Dropbox). The flysystem readStream method will return a resource but BinaryFileResponse needs a string path. Whats the best way to handle this? First download the whole file to the server until response?


Solution

  • You can use the StreamedResponse class for this. You'll have to do some data wiring yourself but it's pretty straight forward. For example, this code was used to enable "forced downloads" for PDF's.

    return new StreamedResponse(function () use ($stream) {
        fpassthru($stream);
        exit();
    }, 200, [
        'Content-Transfer-Encoding', 'binary',
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => sprintf('attachment; filename="%s.pdf"', $filename),
        'Content-Length' => fstat($stream)['size'],
    ]);