5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python+boto3でS3に画像をアップロードして公開する

Last updated at Posted at 2018-12-10

背景

Pythonでboto3ライブラリを使ってAWSのS3に画像をアップロードする際に、セキュリティの設定でデフォルトは読み書き不可にしている場合に、アップロードしたファイルだけ公開したい場合があります。

対応

upload_fileの引数にExtraArgsでjson形式でACLを指定して、公開状態にします。


import os
import boto3

class MyAws():
  def upload_s3(self, original_file_path, upload_folder, upload_filename):
    self.s3 = boto3.client('s3',
      aws_access_key_id=os.getenv('S3_ACCESS_KEY'),
      aws_secret_access_key=os.getenv('S3_SECRET_KEY'),
      region_name=os.getenv('S3_REGION_NAME'))
    upload_filename = os.path.join(folder_name, upload_filename)
    try:
      result = self.s3.upload_file(original_file_path, os.environ["S3_BUCKET_NAME"], upload_filename, ExtraArgs={"ContentType": "image/jpeg", 'ACL':'public-read'})
    except boto3.exceptions.S3UploadFailedError:
      print("S3へのアップロードでエラーが発生しました")
      raise boto3.exceptions.S3UploadFailedError
    finally:
      # 後片付け

参考

5
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?