시작하기전에
본 수업은 'SDK - PHP' 토픽을 선행 학습으로 한다. 따라서 아직 이 수업을 보기 전이라면 꼭 보자.
예제
EC2 인스턴스에 파일을 업로드 하면 PHP가 SDK를 이용해서 S3로 파일을 전송하고, 그 결과를 화면에 출력한다. 이 때 버킷 내에 포함된 모든 객체들의 리스트를 출력한다.
본 예제는 두개의 파일로 이루어져있다.
- s3.html : S3를 사용하기 위한 인증정보와 업로드 할 파일을 선택하고 전송하는 웹페이지
- s3_receiver.php - s3.html을 통해서 업로드한 이미지를 받아서 이를 S3로 전송하고, 그 결과 페이지를 생성해주는 웹에플리케이션
본 예제를 이해하는데 도움이 될만한 수업들은 아래와 같다.
s3.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <!DOCTYPE html> <html> <head> <meta http -equiv = "Content-Type" content= "text/html;charset=utf-8" > </head> <body> <form enctype= "multipart/form-data" action= "s3_receiver.php" method= "POST" > <p><label>key</label><input type = "text" name= "key" /></p> <p><label>secret</label><input type = "text" name= "secret" /></p> <p><label>버킷</label><input type = "Bucket" name= "bucket" /></p> <p><label></label><input name= "userfile" type = "file" /></p> <p><label></label><input type = "submit" value= "업로드" ></p> </form> </body> </html> |
s3_receiver.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | <!DOCTYPE HTML> <html> <head> <meta http-equiv= "Content-Type" content= "text/html;charset=utf-8" > </head> <body> <?php error_reporting (E_ALL); ini_set ( 'display_errors' , 'On' ); $uploaddir = '/tmp/' ; $uploadfile = $uploaddir . basename ( $_FILES [ 'userfile' ][ 'name' ]); if (move_uploaded_file( $_FILES [ 'userfile' ][ 'tmp_name' ], $uploadfile )) { echo "파일이 유효하고, 성공적으로 업로드 되었습니다.\n" ; } else { die ( '업로드에 실패 했습니다' ); } require './vendor/autoload.php' ; use Aws\Common\Aws; use Aws\S3\Enum\CannedAcl; use Aws\Common\Enum\Region; try { // Instantiate an S3 client $s3 = Aws::factory( array ( 'key' => $_POST [ 'key' ], 'secret' => $_POST [ 'secret' ], 'region' =>Region::AP_NORTHEAST_1 ))->get( 's3' ); // Upload a publicly accessible file. File size, file type, and md5 hash are automatically calculated by the SDK $result = $s3 ->putObject( array ( 'Bucket' => $_POST [ 'bucket' ], 'Key' => $_FILES [ 'userfile' ][ 'name' ], 'Body' => fopen ( $uploadfile , 'r' ), 'ACL' => CannedAcl::PUBLIC_READ, 'ContentType' =>mime_content_type( $uploadfile ) )); $list = $s3 ->listObjects( array ( 'Bucket' => $_POST [ 'bucket' ] )); } catch (S3Exception $e ){ print_r( $e ); } ?> <img src= "https://s3-ap-northeast-1.amazonaws.com/opentutorials/<?=$_FILES['userfile']['name']?>" /> <br /> <ul> <?php foreach ( $list [ 'Contents' ] as $object ){ echo "<li><a href=\"https://s3-ap-northeast-1.amazonaws.com/opentutorials/{$object['Key']}\" target=\"_blank\">{$object['Key']}</a></li>" ; } ?> </ul> </body> </html> |