简体   繁体   English

您如何使用适用于PHP的Amazon SDK强制文件从Amazon S3下载?

[英]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. 我有一个使用Amazon S3存储文件的应用程序。 I ran into a problem where a large PDF was not downloading using chrome. 我遇到了一个问题,即没有使用chrome下载大型PDF。 Smaller PDFs work great, but this larger would not work. 较小的PDF可以很好地工作,但是较大的PDF则不能工作。 I don't believe it is an issue with the PDF, I suspect that it has to do with the size of the file. 我不认为这是PDF的问题,我怀疑这与文件的大小有关。

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. 这对于较小的文件非常有用,但是今天我遇到了一个问题,即无法显示大PDF。 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? 如何使用Amazon SDK for PHP强制下载文件?

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. 您的方法存在的问题是,您将整个文件从S3下载到Web服务器的内存中,然后将其发送到用户的浏览器。 If the file is large, this can result in exceeding memory_limit or even max_execution_time . 如果文件很大,则可能导致超过memory_limit甚至max_execution_time (Admittedly, I don't know why your case is Chrome-specific..) (诚​​然,我不知道您的案件为何是特定于Chrome的。)

A more elegant way would be to redirect the user to download the file directly from S3. 一种更优雅的方法是重定向用户以直接从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() . 使用get_object_url()代替get_object()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM