【问题标题】:Download file stored on Amazon S3 with php使用 php 下载存储在 Amazon S3 上的文件
【发布时间】:2015-03-11 04:55:06
【问题描述】:

我有以下代码成功地将 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;

【问题讨论】:

    标签: php amazon-web-services amazon-s3 download


    【解决方案1】:

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

    类似:

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

    并将该 url 传递给用户。这会将用户引导至将开始文件下载的 amzon 页面(该链接将在 5 分钟内有效 - 但您可以更改)

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

    【讨论】:

      【解决方案2】:

      您正在尝试将 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;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-01
        相关资源
        最近更新 更多