首页 > 解决方案 > 如何使用 Multer 和 expressjs 将目标路径作为 file.filename 的图像上传到 Amazon s3

问题描述

我正在使用 Multers3 和 express 将图像上传到 Amazon S3。图片正在上传,但我在将图片上传到正确路径时面临挑战。

例如,在将 Multer 与 s3 集成之前,使用此代码,将图像上传到public/uploads/postImages/the new filename.jpg

 const uploadPath = path.join('public', Post.postImageBasePath)
 const imageMineTypes = ['image/jpeg', 'image/png', 'image/gif']

  const upload = multer({ 

    dest: uploadPath,
     fileFilter:  (req, file, callback) => {
     callback(null, imageMineTypes.includes(file.mimetype) )
    }

 })

但是在将 Multer 与 Amazon S3 集成后,使用此代码,图像现在正在上传到public/uploads/postImages/original file name.jpg

   const uploadPath = path.join('public', Post.postImageBasePath)

const upload = multer({ 

   storage: multerS3({
     s3: s3,
     bucket: bucketname,
     s3BucketEndpoint:true,
     endpoint:"http://" + bucketname + ".s3.amazonaws.com",
     key: function (req, file, cb) {
       cb(null, uploadPath + '/' + file.originalname);
     }
  })

})

如果我想获得新的文件名,那么我可以做这样的事情, req.file.filename但这只能在我的上传中进行,也就是在图像成功上传之后。如果尝试在上述代码中执行此操作,它将显示未定义,因为尚未生成新文件名。下面是我的上传代码。

router.post('/', upload.single('cover'), async (req, res, next) => {
   const fileName = req.file != null ? req.file.filename : null

   const post = new Post({
     title: req.body.title,
     description: req.body.description,
     from: req.body.from,
     postImage: fileName

  })
  try {

  const newPost = await post.save()
  res.redirect('/posts')

  } catch {
  if (post.postImage != null) {
   removePostImage(post.postImage)
  }
   renderNewPage(res, post, true)
 }
});

如何dest: uploadPath,使用 S3 添加路径?这样路径将是 public/uploads/postImages/new file name.jpg

这就是我想要实现的

 const uploadPath = path.join('public', Post.postImageBasePath)
 const imageMineTypes = ['image/jpeg', 'image/png', 'image/gif']

 const upload = multer({ 

   storage: multerS3({
     dest: uploadPath,
     s3: s3,
     bucket: bucketname,
     s3BucketEndpoint:true,
     endpoint:"http://" + bucketname + ".s3.amazonaws.com",
     key: function (req, file, cb) {
       cb(null, uploadPath + '/' + req.file.filename); 
     },
      fileFilter:  (req, file, callback) => {
        callback(null, imageMineTypes.includes(file.mimetype) )
     }
  })
})

总之,我希望图像路径是已生成的新图像名称

标签: node.jsexpressmulter-s3

解决方案


推荐阅读