如何解决使用multer memoryStorage时如何重命名我的原始名称?
我正在尝试在使用 multer memoryStorage 时重命名我的文件 originalname。我正在使用 multer 上传文件数组,当我 console.log(req.files) 我得到:
{
fieldname: 'images',originalname: 'snake.jpg',encoding: '7bit',mimetype: 'image/jpeg',buffer: <Buffer ff d8 38134 more bytes>,size: 38184
}
我想重命名我的原始名称的原因是我将图像存储在 AWS S3 中,如果图像具有相同的名称,它会被更新而不是作为新图像添加。
我尝试通过在存储在数据库中时在原始名称旁边添加日期来这样做,但是当图像添加到存储桶中时原始名称不会更改。
这是我的代码:
posts.js
const storage=multer.memoryStorage()
const upload = multer({
storage: storage,limits: { fieldSize: 25 * 1024 * 1024 },});
router.post(
"/",[ upload.array("images",config.get("maxImageCount")),imageResize,],async (req,res) => {
const paths = await req.files.map((file) => ({ originalName: file.originalname + "-" + new
Date().toISOString() + "-" + uuidv4()}));
await Post.create({
title: req.body.title,userId: req.body.userId,Post_Images: paths.map((x) => ({ images: x.originalName })),},{
include: [Post_Image] }).then(
res.status(201).send())
imageResize.js
const sharp = require("sharp");
require("dotenv").config();
const AWS = require('aws-sdk')
const s3 = new AWS.S3({
accessKeyId: process.env.AWS_ID,secretAccessKey: process.env.AWS_SECRET,region:process.env.AWS_REGION
})
module.exports = async (req,res,next) => {
const images = [];
const resizePromises = req.files.map(async (file) => {
console.log(file)
await sharp(file.buffer)
.resize(2000)
.jpeg({ quality: 50 })
.toBuffer()
.then(resized=>s3.upload({
Bucket:process.env.AWS_BUCKET,Key:file.originalname + "_full.jpg",Body:file.buffer,ACL: 'public-read'
}).promise()),await sharp(file.buffer)
.resize(100)
.jpeg({ quality: 30 })
.toBuffer()
.then(resized=>s3.upload({
Bucket:process.env.AWS_BUCKET,Key:file.originalname + "_thumb.jpg",ACL: 'public-read'
}).promise())
images.push(file.originalname);
});
await Promise.all([...resizePromises]);
req.images = images;
next();
};
换句话说,我试图将我的 req.files 中的 originalname
更改为originalname + "-" + new Date().toISOString() + "-" + uuidv4()
或
如何在我的 posts.js 和 imageResize.js 中保持 uuid 和日期相同?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。