1
4

More than 1 year has passed since last update.

AWS-SDKを利用してS3にファイルをアップロードする

Posted at

備忘録としてAWS-SDKv3を利用したファイルアップロードとダウンロードURLの取得クラスのコードを載せておきます。

ファイルアップロードクラス

StorageFile.ts
import { PutObjectCommand,GetObjectCommand, S3Client } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import setupEnv from '../tests/setupEnv'
import * as fs from 'fs'

const client = new S3Client({})

if(process.env.ENV === undefined){
  setupEnv()
}

export default class StorageFile {
  upload = async(fileName:string) => {
    let filePath = '/tmp/'
    if(process.env.ENV == 'unit_test'){
      filePath = './tests/tmp/'
    }
    const fileContent = fs.readFileSync(filePath+fileName);

    // Setting up S3 upload parameters
    const params = {
        Bucket: process.env.BUCKET_NAME,
        Key: 'public/'+fileName, // File name you want to save as in S3
        Body: fileContent
    }
    const command = new PutObjectCommand(params);

    // Uploading files to the bucket
    try {
      const response = await client.send(command);
      console.log(response);
    } catch (err) {
      console.error(err);
    }
  }
  getUrl = async(fileName:string) => {
    const params = {
        Bucket: process.env.BUCKET_NAME,
        Key: 'public/'+fileName
    }
    const command = new GetObjectCommand(params)
    const url = await getSignedUrl(client, command, { expiresIn: 3600 })
    return url
  }
}

処理の詳細内容

  • StorageFile.upload(fileName)で/tmp/[fileName]のファイルをアップロードします
  • jestでのテストを想定してprocess.env.ENV=='unit_test'の場合だけ参照するフォルダを変えています
  • S3バケットの名前はprocess.env.BUCKET_NAMEから取得しています
  • アップロード後はStorageFile.getUrl(fileName)で期限付きダウンロードURLを取得できます
  • S3にアップロードしたファイルをブラウザで閲覧する場合はS3側で公開設定をすればOKです

まとめ

SDKv2を使った情報はインターネット上で散見されるのですが、SDKv3はまだまだ普及していないようでAWSの公式ドキュメントやAPIドキュメントを参考にしながら作成していきました。
参考にしてください。

1
4
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
1
4