58
45

More than 5 years have passed since last update.

TypeScriptでAWS S3にファイルをアップロードする

Last updated at Posted at 2019-08-24

本稿ではTypeScriptでAWS S3にファイルをアップロードする方法を解説する。

AWS SDKモジュールをインストールする。

yarn add aws-sdk
yarn add -D @types/aws-sdk

ファイルをアップロードする。

import AWS from 'aws-sdk'
import S3 from 'aws-sdk/clients/s3'

AWS.config.logger = console // 通信のデバッグ用。不要であれば削除可。

const accessKeyId = ''; // IAMユーザの認証情報の「アクセスキーID」から確認できます。
const secretAccessKey = ''; // IAMユーザのシークレットアクセスキー。アクセスキーを作ったときだけ見れるやつです。
const bucketName = ''; // 保存先のバケット名

const bucket = new S3({
  accessKeyId: accessKeyId,
  secretAccessKey: secretAccessKey,
  region: 'ap-northeast-1',
})
const param: S3.Types.PutObjectRequest = {
  Bucket: bucketName,
  Key: 'test.txt', // ファイル絶対パス
  Body: 'hello!', // ファイルの内容
  ACL: 'public-read', // インターネットから誰でもダウンロードできるように
  ContentType: 'text/plain',
}
bucket.upload(param, (err: Error, data: S3.ManagedUpload.SendData) => {
  if (err) {
    console.error(err)
  } else {
    console.log('Successfully uploaded file.', data)
  }
})

実行結果

[AWS s3 200 0.154s 0 retries] putObject({ Body: <Buffer 68 65 6c 6c 6f 21>,
  Bucket: 'バケット名',
  Key: 'test.txt',
  ACL: 'public-read',
  ContentType: 'text/plain' })
Successfully uploaded file. { ETag: '"5a8dd3ad0756a93ded72b823b19dd877"',
  Location: 'https://バケット名.s3.ap-northeast-1.amazonaws.com/test.txt',
  key: 'test.txt',
  Key: 'test.txt',
  Bucket: 'バケット名' }

アップロードされたファイルを見る(httpieコマンド使用)。

http https://バケット名.s3-ap-northeast-1.amazonaws.com/test.txt
HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Length: 6
Content-Type: text/plain
Date: Sat, 24 Aug 2019 14:46:02 GMT
ETag: "5a8dd3ad0756a93ded72b823b19dd877"
Last-Modified: Sat, 24 Aug 2019 14:41:50 GMT
Server: AmazonS3
x-amz-id-2: cXpZ+Tyi3A1ddu6ERAafD4Okv/LzQU2AbSoZeIPztmJ6JBoHf8YWBziC4Ss1WPrz23MVwWqPJ4g=
x-amz-request-id: E3497626B98374BF

hello!

AWSの権限設定

上のコードが動いたAWSの権限設定を一応載せておく。

まず、IAMポリシー。ポリシー名はAmazonS3UploadOnlyにした。

AmazonS3UploadOnly
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::<バケット名>/*"
        }
    ]
}

次に、S3バケットポリシー。なお、「パブリックアクセスをすべてブロック」すべてオフ。

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "<ユーザ名など任意の名前>",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::<あなたのAWSの12桁のID>:user/<あなたのIAMユーザ名>"
            },
            "Action": [
                "s3:PutObject",
                "s3:PutObjectAcl"
            ],
            "Resource": "arn:aws:s3:::<バケット名>/*"
        }
    ]
}

s3:PutObjectは、ファイルがアップロードできるようになる。s3:PutObjectAclは、ACL: 'public-read'を使うために必要。

58
45
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
58
45