According to the resource given in the AWS documentation, downloading object can be done with the following code:
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'];
}
According the docs the above code should display a pdf file (in my case), it opens a pdf but says
Failed to load PDF document.
The file is the s3 don't have any issue, I know it the code. But what can I do to the browser to read and also download automatically?
For detail info, I followed this link https://docs.aws.amazon.com/AmazonS3/latest/userguide/download-objects.html and went to using AWS SDKs
EDIT
I changed 'ResponseContentType' => 'plain/text'
to 'ResponseContentType' => 'application/pdf'
, it opened the pdf but now I need to download it
This should most likely be:
'ResponseContentType' => 'application/pdf',
Else it will be transferred as text and will result in a corrupt file.
Adding header in the code like below solved my issue:
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'];
}
I already wrote on EDIT that changing 'ResponseContentType' => 'plain/text'
to 'ResponseContentType' => 'application/pdf'
opened the pdf but I choose to not include ResponseContentType
on my code so that it can it any file type.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.