1
0

Node.jsでS3の署名付きURL取得

Posted at

node.jsで署名付きURL取得するコードサンプルを書きました。
aws-sdk v3を使用しています。

import { S3Client, PutObjectCommand, GetObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';

const s3 = new S3Client({ region: process.env.AWS_REGION });
// 環境変数にあらかじめBUCKET_NAMEを登録しておく
const BUCKET_NAME = process.env.BUCKET_NAME;
const KEY = "hoge"

export const handler = async (event) => {
    const { filename, contentType } = JSON.parse(event.body);
    console.log("body", event.body);

    const params = {
        Bucket: BUCKET_NAME,
        Key: `${KEY}/${filename}`,
        ContentType: contentType,
    };

    const command = new PutObjectCommand(params);
    // オブジェクトダウンロードするときは以下
    // const command = new GetObjectCommand(params);

    try {
        const signedUrl = await getSignedUrl(s3, command, { expiresIn: 3600 }); // 署名の有効期限を設定(例: 1時間)
        return {
          statusCode: 200,
          headers: {
            'Access-Control-Allow-Origin': '*',
          },
          body: JSON.stringify({ url: signedUrl }),
        };
      } catch (err) {
        console.error(err);
        return {
            statusCode: 500,
            headers: {
                'Access-Control-Allow-Origin': '*',
              },
              body: JSON.stringify({ error: "Could not generate signed URL" }),
        };
    }
};
1
0
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
0