在Next.js 14应用程序中实现S3和Mongo文件上传

问题描述 投票:0回答:1

我正在使用 Aws-S3 作为我的项目文件存储之一。下面的代码以表单上传文件,但在调用 POST 方法时,我要检索对象 URL 并将 s3 上传的对象 URL 作为字符串推送到 Mongoose 数据模型。

这是我的 Next.js 14 代码

注意:如果我必须尝试 multer-s3 来获取像 Node.js 这样的位置,那么请分享一个代码示例。

/app/api/s3/route.js

export async function POST(request) {

try {

const formData = await request.formData();

const file = formData.get("file");



if (!file) {

return NextResponse.json({ error: "No file found" }, { status: 400 });

}



const buffer = Buffer.from(await file.arrayBuffer());

const fileName = file.name;

const contentType = file.type;

let folderName = "";



// Determine folderName based on file type

if (contentType.includes("image")) {

folderName = "image";

} else if (contentType === "application/pdf") {

folderName = "pdf";

} else {

return NextResponse.json(

{ error: "Unsupported file type" },

{ status: 400 }

);

}



await uploadFileToS3(buffer, fileName, contentType, folderName);



return NextResponse.json({ success: true, fileName });

} catch (error) {

console.error(error);

return NextResponse.json(

{ error: "Error uploading file" },

{ status: 500 }

);

}

}

这是我的演示数据模型(仅用于理解目的):


{

Photo: {

type: String,

},

export const Team = mongoose.models.Team || mongoose.model("Team", teamSchema);

我想在提交表单时将上传的文件url存储到Mongoose模型中。

amazon-s3 next.js mongoose-schema
1个回答
0
投票

从 @aws-sdk/client-s3 库导入 GetObjectCommand。 从 @aws-sdk/s3-request-presigner 库导入 getSignedUrl。

使用 getSignedUrl 函数获取您最近上传的图像的签名 URL。此 URL 允许访问 S3 存储桶中的图像。 将 URL 保存到 MongoDB。

然后使用 MongoDB 函数将获得的签名 URL 存储到您的 MongoDB 数据库中。

顺便说一句,这就是我在 Express JS 中所做的,但如果您从 NextJS 调用 MongoDB 函数,过程将是相同的。

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

const s3client = new S3Client({
  region: process.env.AWS_REGION,
  credentials: {
    accessKeyId: process.env.AWS_ACCESSKEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESSKEY,
  },
});

我在这里做了一个辅助函数,它在这里接收参数

export const getUrlOfImageFromS3 = async (key) => {
  const command = new GetObjectCommand({
    Bucket: "your bucket name",
    Key: key,
  });

  const url = await getSignedUrl(s3client, command, { expiresIn: 3600 });
  return url;
};


  

const url = 等待 getUrlOfImageFromS3(fileKey); 然后我将这个网址与特定数据保存到 MONGODB。

如果您需要任何进一步的帮助,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.