使用 php 下载存储在 Amazon S3 上的文件


Download file stored on Amazon S3 with php

我有以下代码,它成功地将保存在 S3 上的文件显示到浏览器,但我希望能够将该文件下载到客户端计算机。

我需要做什么?

$result = S3::getObject($Bucketname,$uri);
header("Content-Type: ".$result->headers['type']);
die($result->body);

我已经尝试了以下内容,但它只是下载了一个无法读取的文件......

$result = S3::getObject($Bucketname,$uri);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=test.pdf');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . strlen($result->body));
ob_clean();
flush();
readfile($result->body);
exit;

您可以使用getObjectUrl方法创建下载URL。

像这样:

$downloadUrl = $s3->getObjectUrl($bucketname, $file, '+5 minutes', array(
                'ResponseContentDisposition' => 'attachment; filename=$file,'Content-Type' => 'application/octet-stream',
        ));

并将用户定向到将开始文件下载的 Amzon 页面(链接有效期为 5 分钟 - 但您可以更改它)

另一种选择是首先将该文件保存到您的服务器,然后让用户从您的服务器下载该文件

您正在尝试将 pdf 下载为二进制内容类型数据。

使用 getObject 请求的响应来获取正确的 MIME 类型:

$result = S3::getObject($Bucketname,$uri);
header('Content-Description: File Transfer');
header('Content-Type: ' . $result['ContentType']);
header('Content-Disposition: attachment; filename=test.pdf');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . strlen($result->body));
ob_clean();
flush();
readfile($result->body);
exit;