首页 > 解决方案 > 无法使用 Node.js 将图像发布到 aws-s3 服务

问题描述

我正在尝试将图像添加到 AWS 的 S3 服务。当 S3 存储桶中有图像时,我的 get 服务有效,但问题是我无法从本地存储中添加任何图像。

这是我的代码:

const router = require('express').Router()
const multer = require('multer')
const AWS = require('aws-sdk')

const s3 = new AWS.S3({
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    region: 'eu-central-1',
    signatureVersion: 'v4'
})

const upload = multer({
    limits: {
        fileSize: 1024 * 1024 * 3 // 3 mb file
    },
    fileFilter(req, file, cb) {
        if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/jpg' || file.mimetype === 'image/png') {
            return cb(undefined, true)
        }
        cb(new Error('Please upload an image format!'))
    }
})


router.put('/logo', upload.single("file"), async (req, res) => {
    const logoImage = req.file.buffer
    
    // I get the buffer correctly from the Postman
    if (!logoImage) {
        return res.status(400).send('No logo selected!')
    }
    try {
        const result = await s3.getSignedUrlPromise('putObject', {
            Bucket: 's3-logo',
            Key: `custom-logo/logo.jpeg`,
            ContentType: 'image/jpeg',
            Body: logoImage
        })
        res.send(result)
    } catch (error) {
        next(error)
    }
})

结果给了我一个长 URL,但是当我尝试打开 URL 时,我收到以下错误:

<Code>SignatureDoesNotMatch</Code>
<Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message>

我的存储桶策略:

{
    "Version": "2012-10-17",
    "Id": "Policy1612115601431",
    "Statement": [
        {
            "Sid": "Stmt1612115598599",
            "Effect": "Allow",
            "Principal": "*",
            "Action": [
                "s3:DeleteObject",
                "s3:GetObject",
                "s3:PutObject"
            ],
            "Resource": "arn:aws:s3:::s3-logo/*"
        }
    ]
}

标签: node.jsamazon-web-servicesamazon-s3

解决方案


推荐阅读