首页 > 解决方案 > unable to display aws s3 object but downloads

问题描述

PHP/AWS S3 rookie here: working on a project where I need to be able to display both an album artwork from AWS S3 bucket as well as play a music file. I can upload, but when trying to view image, it downloads instead. Have checked the content-type and content disposition. I believe the problem is around this snippet of code: I would appreciate any help/suggestions.

<?php
....
....
try {
$s3 = S3Client::factory(
  array(
    'credentials' => array(
      'key' => $IAM_KEY,
      'secret' => $IAM_SECRET
    ),
    'version' => 'latest',
    'region'  => 'us-east-2'
  )
);
//
$result = $s3->getObject(array(
  'Bucket' => $BUCKET_NAME,
  'Key'    => $keyPath
));
echo $result;
//exit();
// Display it in the browser
header("Content-Type: {$result['ContentType']}");
header('Content-Disposition: filename="' . basename($keyPath) . '"');
return $result['Body'];
} catch (Exception $e) {
   die("Error: " . $e->getMessage());
}
?>
<!DOCTYPE html>
<html>
  <head>
    <title>display image</title>
 </head>
 <body>
   <img src="<?php echo $result['body']; ?>">
 </body>
</html>

标签: phpamazon-web-servicesamazon-s3

解决方案


从这个答案中引用/被盗:

您可以从 S3 下载内容(在 PHP 脚本中),然后使用正确的标头提供它们。

作为一个粗略的例子,假设您在 image.php 中有以下内容:

$s3 = new AmazonS3();
$response = $s3->get_object($bucket, $image_name);
if (!$response->isOK()) {
    throw new Exception('Error downloading file from S3');
}
header("Content-Type: image/jpeg");
header("Content-Length: " . strlen($response->body));
die($response->body);
Then in your HTML code, you can do

<img src="image.php">

推荐阅读