Skip to content
Advertisement

Laravel 5.1 – how to download pdf file from S3 bucket

I am using Laravel’s Storage facade and I am able to upload the pdf to S3 and I am also able to get() its contents but I cannot display or download it to the end user as an actual pdf file. It just looks like raw data. Here is the code:

$file = Storage::disk($storageLocation)->get($urlToPDF);
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename='file.pdf'");
echo $file;

How can this be done? I have checked several articles (and SO) and none of them have worked for me.

Advertisement

Answer

I think something like this will do the job in L5.2:

public function download($path)
{
    $fs = Storage::getDriver();
    $stream = $fs->readStream($path);
    return Response::stream(function() use($stream) {
        fpassthru($stream);
    }, 200, [
        "Content-Type" => $fs->getMimetype($path),
        "Content-Length" => $fs->getSize($path),
        "Content-disposition" => "attachment; filename="" .basename($path) . """,
        ]);
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement