You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS Lambda部署的后端上传图片至S3时出现404错误的排查求助

AWS Lambda部署的后端上传图片至S3时出现问题的排查求助

大家好,我遇到了一个棘手的问题:本地运行的Node.js后端可以正常将文件上传到S3,但部署到AWS Lambda之后就失效了。下面是我的相关代码、配置和已经完成的权限配置,麻烦各位帮忙排查一下问题所在?


1. S3核心配置文件(config/aws.js)

import dotenv from "dotenv";
dotenv.config();
import AWS from "aws-sdk";

if (process.env.NODE_ENV === "development") {
  AWS.config.update({
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  });
}

AWS.config.update({
  region: "us-east-1",
});

const s3 = new AWS.S3();
export default s3;

2. S3上传逻辑与博客创建接口

import Blog from "../models/blog.js";
import s3 from "../config/aws.js";
import mime from "mime-types";
import { v4 as uuidv4 } from "uuid";

const uploadToS3 = async (file, folder) => {
  const ext = mime.extension(file.mimetype || "image/jpeg") || "jpg";
  let contentType = file.mimetype;

  if (!contentType) {
    if (ext === "webp") contentType = "image/webp";
    else if (ext === "png") contentType = "image/png";
    else if (ext === "jpg" || ext === "jpeg") contentType = "image/jpeg";
    else contentType = "application/octet-stream"; // fallback
  }

  const key = `${folder}/${uuidv4()}.${ext}`;
  const result = await s3.upload({
    Bucket: process.env.AWS_BUCKET_NAME,
    Key: key,
    Body: file.buffer,
    ContentType: contentType,
  }).promise();

  return result.Location;
};

export const createBlog = async (req, res) => {
  try {
    const { title, metaTitle, metaDescription, content, sections, author, datePosted } = req.body;
    let coverImage = "";
    let bannerImage = "";

    if (req.files?.coverImage?.[0]) {
      coverImage = await uploadToS3(req.files.coverImage[0], "blogs/cover", req.files.coverImage[0].originalname);
    }
    if (req.files?.bannerImage?.[0]) {
      bannerImage = await uploadToS3(req.files.bannerImage[0], "blogs/banner", req.files.bannerImage[0].originalname);
    }

    const blog = await Blog.create({
      title,
      metaTitle,
      metaDescription,
      content,
      sections: JSON.parse(sections || "[]"),
      coverImage,
      bannerImage,
      author,
      datePosted: datePosted || new Date(),
    });

    res.status(201).json({ success: true, blog });
  } catch (err) {
    console.error("❌ Error creating blog:", err);
    res.status(500).json({ success: false, message: "Server Error" });
  }
};

3. S3 Bucket策略

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowPublicReadForAllObjects",
      "Effect": "Allow",
      "Principal": "*",
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::arcnaturalbucket/*"
    },
    {
      "Sid": "AllowCloudFrontServicePrincipal",
      "Effect": "Allow",
      "Principal": {
        "Service": "cloudfront.amazonaws.com"
      },
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::arcnaturalbucket/*",
      "Condition": {
        "ArnLike": {
          "AWS:SourceArn": "arn:aws:cloudfront::148761674610:distribution/EJ61YDSVUO9GZ"
        }
      }
    }
  ]
}

4. 已配置的权限说明

  • 部署在Lambda上的后端,已经分配了S3全访问权限的IAM角色
  • Bucket已配置公共读权限,同时授权了CloudFront的访问权限

5. package.json关键依赖

{
  "name": "backend",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "start": "nodemon server.js"
  },
  "dependencies": {
    "@sendgrid/mail": "^8.1.4",
    "aws-sdk": "^2.1692.0",
    "aws-serverless-express": "^3.4.0",
    "axios": "^1.8.4",
    "bcrypt": "^5.1.1",
    "bcryptjs": "^3.0.2",
    "body-parser": "^1.20.3",
    "cookie-parser": "^1.4.6",
    "cors": "^2.8.5",
    "crypto": "^1.0.1",
    "date-fns": "^4.1.0",
    "dotenv": "^10.0.0",
    "exceljs": "^4.4.0",
    "express": "^4.21.2",
    "express-session": "^1.18.1",
    "express-validator": "^7.2.1",
    "form-data": "^4.0.2",
    "fs": "^0.0.1-security",
    "helmet": "^8.1.0",
    "json2csv": "^6.0.0-alpha.2",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^8.13.2",
    "morgan": "^1.10.0",
    "multer": "^1.4.5-lts.1",
    "multer-s3": "^3.0.1",
    "node-cron": "^3.0.3",
    "node-fetch": "^3.3.2",
    "nodemailer": "^6.10.1",
    "nodemon": "^2.0.15",
    "open": "^10.1.2"
  }
}

目前的疑问

  1. 本地环境完全正常,Lambda部署后失效,可能是Lambda执行环境的特殊限制导致的吗?比如文件buffer的处理方式?
  2. 权限配置有没有遗漏?比如Lambda的IAM角色是否真的正确生效?
  3. 环境变量是否可能存在问题?比如process.env中的S3相关变量在Lambda上没有正确加载?
  4. 有没有其他容易被忽略的Lambda与S3交互的坑?

麻烦各位帮忙分析一下,谢谢!

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 10:04:31