코드
- KEY, SECRET, BUCKET, $source는 상황에 맞게 설정
<?php
require '../../vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
use Aws\S3\MultipartUploader;
use Aws\Exception\MultipartUploadException;
$s3Client = new S3Client([
'version' => 'latest',
'region' => 'ap-northeast-2',
'credentials' => [
'key' => '[KEY]',
'secret' => '[SECRET]'
]
]);
$bucket = '[BUCKET]';
$source = 'sample.mp4';
$uploadKey = uniqid('video_', true) . '.' . end(explode('.', $source));
$uploader = new MultipartUploader($s3Client, $source, [
'bucket' => $bucket,
'key' => $uploadKey,
]);
try {
$result = $uploader->upload();
echo "Upload complete: {$result['ObjectURL']}\n";
} catch (MultipartUploadException $e) {
echo $e->getMessage() . "\n";
}
공식 사이트 샘플코드
<?php
// AWS S3 테스트 코드 시작
require '/vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
use Aws\S3\MultipartUploader;
use Aws\Exception\MultipartUploadException;
$s3Client = new S3Client([
'profile' => 'default',
'region' => 'us-east-2',
'version' => '2006-03-01'
]);
$bucket = 'your-bucket';
$key = 'my-file.zip';
// Using stream instead of file path
$source = fopen('/path/to/large/file.zip', 'rb');
$uploader = new ObjectUploader(
$s3Client,
$bucket,
$key,
$source
);
do {
try {
$result = $uploader->upload();
if ($result["@metadata"]["statusCode"] == '200') {
print('<p>File successfully uploaded to ' . $result["ObjectURL"] . '.</p>');
}
print($result);
} catch (MultipartUploadException $e) {
rewind($source);
$uploader = new MultipartUploader($s3Client, $source, [
'state' => $e->getState(),
]);
}
} while (!isset($result));
fclose($source);
// 끝
AWS console
- 파일 업로드가 가능하도록 S3 버킷에 권한 추가. Resource와 SourceIP 정보는 상황에 맞게 변경
관련 링크
블로그 링크