[英]Download file from Amazon S3 with lumen/php
根據AWS文檔中給出的資源,可以使用以下代碼下載object:
public function download($folder, $file)
{
$s3 = new S3Client([
'region' => env('AWS_REGION'),
'version'=>'latest',
'credentials' => [
'key' =>env('AWS_ACCESS_KEY_ID'),
'secret' =>env('AWS_SECRET_ACCESS_KEY')
],
]);
$result = $s3->getObject([
'Bucket' => env('AWS_BUCKET'),
'Key' => $folder.'/'.$file,
'ResponseContentType' => 'text/plain',
'ResponseContentLanguage' => 'en-US',
'ResponseContentDisposition' => 'attachment; filename='.$file,
'ResponseCacheControl' => 'No-cache',
'ResponseExpires' => gmdate(DATE_RFC2822, time() + 3600),
]);
header("Content-Type: {$result['ContentType']}");
echo $result['Body'];
}
根據文檔,上面的代碼應該顯示一個 pdf 文件(在我的情況下),它會打開一個 pdf 但說
加載 PDF 文檔失敗。
該文件是 s3 沒有任何問題,我知道它的代碼。 但是我可以對瀏覽器做些什么來閱讀和自動下載呢?
有關詳細信息,我點擊此鏈接https://docs.aws.amazon.com/AmazonS3/latest/userguide/download-objects.html並使用 AWS 開發工具包
編輯
我將'ResponseContentType' => 'plain/text'
更改為'ResponseContentType' => 'application/pdf'
,它打開了 pdf 但現在我需要下載它
這很可能是:
'ResponseContentType' => 'application/pdf',
否則它將作為文本傳輸並導致文件損壞。
在如下代碼中添加 header 解決了我的問題:
public function download($folder, $file)
{
$s3 = new S3Client([
'region' => env('AWS_REGION'),
'version'=>'latest',
'credentials' => [
'key' =>env('AWS_ACCESS_KEY_ID'),
'secret' =>env('AWS_SECRET_ACCESS_KEY')
],
]);
$result = $s3->getObject([
'Bucket' => env('AWS_BUCKET'),
'Key' => $folder.'/'.$file,
'ResponseContentLanguage' => 'en-US',
'ResponseCacheControl' => 'No-cache',
'ResponseExpires' => gmdate(DATE_RFC2822, time() + 3600),
]);
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=" . $file);
header("Content-Type: {$result['ContentType']}");
echo $result['Body'];
}
我已經在EDIT上寫道,將'ResponseContentType' => 'plain/text'
更改為'ResponseContentType' => 'application/pdf'
打開了 pdf 但我選擇不在我的代碼中包含ResponseContentType
以便它可以處理任何文件類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.