[英]Download file stored on Amazon S3 with php
I have the following code which successfully displays a file saved on S3 to the browser, but I would like to be able to download the file to the client's computer. 我有以下代码可以成功将保存在S3上的文件显示到浏览器中,但是我希望能够将文件下载到客户端计算机上。
What do I need to do? 我需要做什么?
$result = S3::getObject($Bucketname,$uri);
header("Content-Type: ".$result->headers['type']);
die($result->body);
I've tried the following, but it just downloads an unreadable file... 我已经尝试了以下方法,但是它只是下载了无法读取的文件...
$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;
you can create a download url, using the getObjectUrl method 您可以使用getObjectUrl方法创建下载网址
somthing like: 像这样的东西:
$downloadUrl = $s3->getObjectUrl($bucketname, $file, '+5 minutes', array(
'ResponseContentDisposition' => 'attachment; filename=$file,'Content-Type' => 'application/octet-stream',
));
and pass that url to the user. 并将该网址传递给用户。 that will direct the user to an amzon page which will start the file download (the link will be valid for 5 minutes - but you can change that)
会将用户定向到amzon页面,该页面将开始文件下载(链接的有效期为5分钟-但您可以更改该链接)
another option, is first saving that file to your server, and then let the user download the file from your server 另一个选择是,首先将文件保存到服务器,然后让用户从服务器下载文件
You're trying to download a pdf as a binary content type data. 您正在尝试下载pdf作为二进制内容类型数据。
Use the response of your getObject request to get the proper mime type: 使用您的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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.