Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
S3のContent-Dispositionダウンロードテスト
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>S3 Download Test</title>
</head>
<body>
<h1>S3 Download Test</h1>
<ul>
<?php
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
$typeTable = [
'UTF-8 Raw',
'UTF-8 URL Encoded',
'UTF-8 Base64 Encoded',
'RFC 5987',
'Shift_JIS Raw',
'Shift_JIS URL Encoded'
];
/**
* Content-Dispositionヘッダの値をタイプによって作成
* @param $type
* @param $fileName
* @return string
*/
function createContentDisposition($type, $fileName) {
$result = '';
switch($type) {
case 'UTF-8 Raw' :
$result = 'attachment; filename="' . $fileName . '"';
break;
case 'UTF-8 URL Encoded' :
$result = 'attachment; filename="' . rawurlencode($fileName) . '"';
break;
case 'UTF-8 Base64 Encoded' :
$result = 'attachment; filename="=?utf-8?B?' . base64_encode($fileName). '?="';
break;
case 'RFC 5987' :
$result = 'attachment; filename*=UTF-8\'\'' . rawurlencode($fileName);
break;
case 'Shift_JIS Raw' :
$result = 'attachment; filename="' . mb_convert_encoding($fileName, 'Shift_JIS', 'UTF-8') . '"';
break;
case 'Shift_JIS URL Encoded' :
$result = 'attachment; filename="' . rawurlencode(mb_convert_encoding($fileName, 'Shift_JIS', 'UTF-8')) . '"';
break;
}
return $result;
}
/**
* AWS SDK v3 S3Clientを利用して署名付きURL作成
* @param $s3Client
* @param $bucketName
* @param $bucketKey
* @param string $expire
* @param array $options
* @return string
*/
function createPresignedUrl($s3Client, $bucketName, $bucketKey, $expire = '+10 minutes', $options = [])
{
$options['Bucket'] = $bucketName;
$options['Key'] = $bucketKey;
$cmd = $s3Client->getCommand('GetObject', $options);
$request = $s3Client->createPresignedRequest($cmd, $expire);
return (string) $request->getUri();
}
try {
$s3Client = S3Client::factory([
'version' => 'latest',
'region' => 'ap-northeast-1',
'credentials' => array(
'key' => getenv('AWS_ACCESS_KEY_ID'),
'secret' => getenv('AWS_SECRET_KEY'),
),
]);
$fileName = 's3-test-file.png';
$downloadFileName = '日本語.png';
$filePath = 'path/to';
$bucketName = 'bucketName';
$bucketKey = $filePath . '/' . $fileName;
foreach ($typeTable as $type) {
$url = createPresignedUrl(
$s3Client,
$bucketName,
$bucketKey,
'+20 minutes',
['ResponseContentDisposition' => createContentDisposition($type, $downloadFileName)]
);
echo '<li><a href="' . $url . '">' . $type . ': ' . $downloadFileName . '</a></li>' . PHP_EOL;
}
} catch (S3Exception $e) {
echo $e->getMessage() . PHP_EOL;
}
?>
</ul>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.