Jon Jon - 4 months ago 19x
PHP Question

Certain .pdf File Downloads Damaged In Browser / Acrobat Pro - Using Laravel & AWS S3

I am successfully uploading .pdf files to my AWS S3 bucket using Laravel 5.2. I can go directly to the bucket on AWS S3 and download each .pdf without problem. When I attempt to download certain .pdfs using the code below, the file is unable to be opened by the browser or Acrobat Pro. Here is the code:

$file = Storage::disk('s3')->get($myfile);

// Set headers and force download
echo $file;

In the browser I get the following error:
Failed to load PDF document

In Acrobat Pro, I get the following error:
There was an error opening this document. The file is damaged and could not be repaired.

The .pdf is able to be opened successfully in other Apple programs, such as Preview or Skim. Also, an older .pdf file is able to be uploaded and downloaded successfully.

Jon Jon

While I am not clear what the issue was with the previous use of echo $file;, this now works when revised to use the Laravel method return Response::make($file, 200, $headers);.

// Get the file from s3
$file = Storage::disk('s3')->get($myfile);

// Set headers
$headers = array(
    'Content-type' => 'application/pdf',
    'Content-Disposition'   => 'attachment; filename=filename=file.pdf"

// Download
return Response::make($file, 200, $headers);