1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【備忘録】NextからCloudflare R2に画像アップロードする

Posted at

はじめに

NextからCloudflare R2に画像をアップロードする方法の備忘録です。

ライブラリ

npm install @aws-sdk/client-s3

Cloudflare R2のアクセストークンを取得する

1.R2のAPIトークンを生成する
2. アクセスキーとシークレットキーとエンドポイントを.envに張り付けておく

.env
R2_ACCESS_KEY="XXXX"
R2_SECRET_KEY="XXXX"
R2_ENDPOINT="https://XXXX.r2.cloudflarestorage.com"

Route HandlerからR2へ保存する

keyがアップロード時のパスになります。

import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";

export async function POST(req: Request, res: Response) {
    const formData = await req.formData();
    const imageFileData = formData.get("imageFIleData") as File;
    const imageFileDataArrayBuffer = await imageFileData.arrayBuffer();
    const imageFileDataBuffer = Buffer.from(imageFileDataArrayBuffer);

    // R2アップロードロジック
    const s3 = new S3Client({
        region: "auto",
        endpoint: process.env.R2_ENDPOINT!,
        credentials: {
            accessKeyId: process.env.R2_ACCESS_KEY!,
            secretAccessKey: process.env.R2_SECRET_KEY!
        }
    });
    const response = await s3.send(new PutObjectCommand({
        Bucket: "portfolio-images",
        Key: "test",    // keyに対してポートフォリオのID入れて管理しておく?
        ContentType: imageFileData.type,
        Body: imageFileDataBuffer,
    }));


    return Response.json({
        "message": "アップロードに成功しました。"
    })
}
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?