php - 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>
解决方案
从这个答案中引用/被盗:
您可以从 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">
推荐阅读
- swift - swift 自定义数据类型转换为现有数据类型
- flutter - 自动展开/折叠 SliverAppBar
- amazon-web-services - EC2 实例未加入 ECS 集群
- mongodb - 无法从 mongoDB Compass 连接到 atlas cluster db
- mysql - 在 Laravel 中获取逆关系
- css - 在 React 中覆盖 Material UI 中的样式
- c++ - 初学者C++嵌套循环练习题
- android-studio - 更新后 Android Studio Flutter 错误
- python - 所以我的 Jinga 代码没有输出选项
- python - 删除白色矩形 KivyMD MDExpansionPanel