Jason
Jason

Reputation: 2727

How do you force a file to download from Amazon S3 using the Amazon SDK for PHP?

I have an app that is using the Amazon S3 for storing files. I ran into a problem where a large PDF was not downloading using chrome. Smaller PDFs work great, but this larger would not work. I don't believe it is an issue with the PDF, I suspect that it has to do with the size of the file.

When viewing the file in the browser here is the code I am using:

header("Content-type: $filetype");
header("Content-Disposition: filename=\"".$filename."\"");
$response = $s3->get_object(AMAZON_BUCKET, $filepath);   
echo $response->body;

This works great for smaller files, but today I ran into a problem where this large PDF would not show. I am thinking the file is too big to be rendered. Therefore I decided to try to force files to be downloaded instead of viewed in the browser if they are too big. So here is the code I am trying to get to work, but I must be doing something wrong because it is not working.

    $response = $s3->get_object(AMAZON_BUCKET, $filepath, array(
      'response' => array(
        'content-type' => $filetype,
        'content-disposition' => 'attachment'
       )
    ));

How do I use the Amazon SDK for PHP to force a large file to download?

Upvotes: 1

Views: 2894

Answers (1)

pixelistik
pixelistik

Reputation: 7830

The problem with your approach is that you download the entire file from S3 to your webserver's memory and then send it to the user's browser. If the file is large, this can result in exceeding memory_limit or even max_execution_time. (Admittedly, I don't know why your case is Chrome-specific..)

A more elegant way would be to redirect the user to download the file directly from S3. You can even set custom headers to be part of your request, so you can force the download dialog. Use get_object_url() instead of get_object().

Upvotes: 1

Related Questions