node.js - 如何使用 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) )
}
})
})
总之,我希望图像路径是已生成的新图像名称
解决方案
推荐阅读
- python - Numpy:非相邻值的差异
- django - Django 数据表.net
- laravel - laravel eloquent中如何限制children的属性记录
- javascript - 如何更改html的输入法
- python - 合并两个 pandas 系列,删除 na 值
- javascript - 通过java更新photoshop中的链接文件
- azure - Az MySql 到 Az SQL Server - Data Lake Gen2
- scheme - 为什么应用映射和表达式列表只返回一个布尔值?
- docker-compose - 使用 Docker Compose 将 Asp.Net ABP angular 和 asp.net core 部署到 Azure
- java - 在 MongoDB 上插入多个 CSV 文件时出现批量写入操作错误