使用 s3 存储桶将图像上传到 AWS

问题描述 投票:0回答:1
import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
import uniqid from "uniqid"

    export async function POST(req){
    const data = await req.formData();
    if(data.get('file')){
        // console.log('File Uploaded', data.get('file'))
        // uploading the file to aws s3
        const file = data.get('file')

        const s3Client = new S3Client({
            region : 'eu-north-1',
            credentials : {
                accessKeyId : process.env.AWS_ACCESS_KEY,
                secretAccessKey : process.env.AWS_SECRET_KEY,
            },
        });

        const ext = file.name.split('.').slice(-1)[0] //take the images with.jpeg.jpg etc extension
        const newFileName = uniqid()  + '.' + ext  //to get some random string
        // console.log({newFileName});

        const chunks = [];
        for await (const chunk of file.stream()){
            chunks.push(chunk)
        }

        const buffer = Buffer.concat(chunks)

        const bucket = "food-ordering-system"
        await s3Client.send(new PutObjectCommand({
            Bucket : bucket,
            Key : newFileName,
            ACL : 'public-read', //for file to be publicly available
            ContentType : file.type,
            Body : buffer,
        }));
        
        const link = 'https://'+bucket+'.s3.amazonaws.com/'+ newFileName
        return Response.json(link);
    }
    return Response.json(true)
}

这会导致 500 内部服务器错误,并在终端中显示以下消息:

⨯ TypeError:aws_sdk_client_s3__WEBPACK_IMPORTED_MODULE_0_.S3Client.send 不是函数 在 POST (webpack-internal:///(rsc)/./src/app/api/upload/route.jsx:35:72)

我几乎尝试了一切,但结果没有改善。

node.js amazon-web-services amazon-s3 error-handling
1个回答
0
投票

尝试使用boto3 这是代码

import boto3
access_key_id = ""
secret_access_key = ""
region=""
s3 = boto3.client('s3',
                  access_key_id=access_key_id,
                  secret_access_key=secret_access_key,
                  region=region)
file = ""
bucketname = ""
objectname = ""
with open(file, "rb") as f:
    s3.upload_fileobj(f, bucketname, objectname)

确保添加您的 access_key_id、secert_access_key、区域、文件(文件路径)、存储桶名称、对象名称

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