javascript 图像张贴到awss3变成没有类型

xwbd5t1u  于 2022-12-21  发布在  Java
关注(0)|答案(1)|浏览(103)

我正在建立一个快速应用程序,并试图上传图像到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 empty,并且生成的对象URL不可用:enter image description here
这是当我使用s3直接添加图像时的样子,对象URL返回完整的图像:enter image description here
我哪一步做错了?2预先谢谢你的帮助!
我在Google上找不到这样的问题,我希望对象URL可以正常工作,并在我的html文件的src属性中使用它来显示照片。

ajsxfq5m

ajsxfq5m1#

我没有使用过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());
    },
  }),
});

希望这能解决您的问题

相关问题