Next.js Discord

Discord Forum

s3 image upload, connection and upload to s3 giving error

Unanswered
Waterman posted this in #help-forum
Open in Discord
Avatar
WatermanOP
I appreciate all help, don't really know if the packages I am using are the right ones, just did like the tutorial and hes not using next 13
and is the general setup of my s3 upload correct? Thanks 🙂

I might have some outdated code so what I think is causing trouble is:
code...
import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";   <---- correct import?
code...

const client = new S3Client({
    region: "eu-north-1",
    credentials: {
      accessKeyId: process.env.S3_ACCESS_KEY_ID,
      secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
    },
});

code...



FULL CODE BELOW


Errors:
displayed as picture below



Code
import { NextRequest, NextResponse } from "next/server";
import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";


export const POST = async (req: NextRequest) => {
  const formData = await req.formData();
  const file = formData.get("file");

  const client = new S3Client({
    region: "eu-north-1",
    credentials: {
      accessKeyId: process.env.S3_ACCESS_KEY_ID,
      secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
    },
  });

  const links = [];

  for (const file of formData.getAll("file")) {
    const ext = file.type.split("/").pop();
    const newFileName = `${Date.now()}-${Math.random()
      .toString(36)
      .substring(2, 15)}.${ext}`;

    const fileBuffer = await file.arrayBuffer();
    const fileUint8Array = new Uint8Array(fileBuffer);

    client.send(
      new PutObjectCommand({
        Bucket: "nextjsleflyxbuckle",
        Key: newFileName,
        Body: fileUint8Array,
        ACL: "public-read",
        ContentType: file.type,
      })
    );
    const link = `https://nextjsleflyxbuckle.s3.eu-north-1.amazonaws.com/${newFileName}`;
    links.push(link);
  }

  return NextResponse.json({ links });
};
Image

0 Replies