【问题标题】:image post to aws s3 turns into no type图片发布到 aws s3 变成无类型
【发布时间】:2022-12-20 21:06:23
【问题描述】:

我正在构建一个快速应用程序并尝试使用 post 方法将图像上传到 s3, 这是我的AWS配置:

const aws = require("aws-sdk");
const multer = require("multer");
const multerS3 = require("multer-s3-v2");

const s3 = new aws.S3();

aws.config.update({
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  accessKeyId: process.env.AWS_ACCESS_KEY_ID,
  region: "ca-central-1",
});

const fileFilter = (req, file, cb) => {
  if (file.mimetype === "image/jpeg" || file.mimetype === "image/png") {
    cb(null, true);
  } else {
    cb(new Error("Invalid file type, only JPEG and PNG is allowed!"), false);
  }
};

const upload = multer({
  fileFilter,
  storage: multerS3({
    acl: "public-read",
    s3,
    bucket: "yelpcampimage",
    metadata: function (req, file, cb) {
      cb(null, { fieldName: "TESTING_METADATA" });
    },
    key: function (req, file, cb) {
      cb(null, Date.now().toString());
    },
  }),
});

module.exports = upload;

和我的 js 代码的一部分:

router
  .route("/")
  .get(catchAsync(campgrounds.index))
  .post(
    isLoggedIn,
    upload2.single("image"),
    validateCampground,
    catchAsync(campgrounds.createCampground)
  );

当我使用 console.log(req.file) 时,文件类型是“image/png”,

{
  fieldname: 'image',
  originalname: 'c1.png',
  encoding: '7bit',
  mimetype: 'image/png',
  size: 15876,
  bucket: 'yelpcampimage',
  key: '1671537988619',
  acl: 'public-read',
  contentType: 'application/octet-stream',
  contentDisposition: null,
  storageClass: 'STANDARD',
  serverSideEncryption: null,
  metadata: { fieldName: 'TESTING_METADATA' },
  location: 'https://yelpcampimage.s3.ca-central-1.amazonaws.com/1671537988619',
  etag: '"af821b58730de95a15c28b9a5dee3422"',
  versionId: undefined
}

但是当我在aws s3中查看图片时,它变成了typeof为空,并且生成的对象URL无法使用: enter image description here

这是我使用 s3 直接添加图像时的样子,对象 URL 返回完整图像: enter image description here

我哪一步做错了?我在这里先向您的帮助表示感谢!

我在谷歌上找不到这样的问题。我希望对象 URL 可以工作,并在我的 html 文件的 src arrtibute 中使用它来显示照片。

【问题讨论】:

    标签: javascript amazon-web-services express amazon-s3


    【解决方案1】:

    我没有使用过 AWS,但据我了解,您需要设置内容类型。这是我从你使用的包中找到的 ContentType

    并且在您的代码中应该添加

    const upload = multer({
          fileFilter,
          storage: multerS3({
          acl: "public-read",
          s3,
          bucket: "yelpcampimage",
          contentType: multerS3.AUTO_CONTENT_TYPE, //added line
          metadata: function (req, file, cb) {
          cb(null, { fieldName: "TESTING_METADATA" });
         },
       key: function (req, file, cb) {
        cb(null, Date.now().toString());
        },
      }),
    });
    

    希望这能解决您的问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-14
      • 2019-11-20
      • 1970-01-01
      • 2017-01-29
      • 2021-02-28
      • 2015-05-14
      • 2016-05-05
      • 1970-01-01
      相关资源
      最近更新 更多