1. Boto3란?

  • Python을 AWS CLI에서 사용하기 위한 AWS SDK(Software Development Kit)
  • Boto3를 사용하면 Python 애플리케이션, 라이브러리 또는 스크립트를 Amazon S3, Amazon EC2, Amazon DynamoDB 등 AWS 서비스와 쉽게 통합할 수 있습니다

 

2. 사용법

  • app.py
import boto3
from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

@app.route('/')
def main():
    return render_template('index.html')

@app.route('/fileupload', methods=['POST'])
def file_upload():
    file = request.files['file']
    s3 = boto3.client('s3')
    s3.put_object(
        ACL="public-read",
        Bucket="{버킷이름}",
        Body=file,
        Key=file.filename,
        ContentType=file.content_type)
    return jsonify({'result': 'success'})

if __name__ == '__main__':
    app.run()

* key : s3에 업로드 되는 파일 이름

* ContentType : 파일의 타입 ex) jpg, png 등등

 

브라우저에 업로드된 파일(이미지 등) 을 불러오는 법 :  버킷 - 파일에 객체 url을 html 파일에 심어주면 된다

맨 뒤의 파일명만 {파일명} 처리해서 작성해주면 됨!

https://s3-bucket-cors-origin08.s3.ap-northeast-2.amazonaws.com/test2.PNG

 

  • HTML
<div id="post-box" class="form-post">
        <div>
            <div class="form-group">
                <form id="upload-file">
                    <label for="post-url">이미지 파일</label>
                    <input type="file" name="file"/>
                </form>
            </div>
            <button type="button" class="btn btn-primary" onclick="save()">저장</button>
        </div>
    </div>

 

  • script
<script>
        function save() {
            var form_data = new FormData($('#upload-file')[0]);
            $.ajax({
                type: 'POST',
                url: '/fileupload',
                data: form_data,
                processData: false,
                contentType: false,
                success: function (data) {
                    alert("파일이 업로드 되었습니다!!");
                },
            });
        }
    </script>

 

IAM으로 사용자 설정하기

2022.04.25 - [프로그래밍/AWS] - IAM 이용하여 AWS SDK를 이용한 S3 파일 업로드

+ Recent posts