How to rename my originalname when using multer memoryStorage?

心已入冬 提交于 2021-01-05 07:28:20

问题


i am trying to rename my file originalname when using multer memoryStorage. I am using multer to upload an array of files and when i console.log(req.files) i get:

{
fieldname: 'images',
originalname: 'snake.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
buffer: <Buffer ff d8 38134 more bytes>,
size: 38184
}

The reason i want to rename my originalname is i am storing the images in AWS S3 and if the images have the same name it gets updated not added as a new image.

I have tried doing so by adding the date next to the originalname when storing in database but then originalname does not change when the images get added in bucket.

Here is my code:

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",
    Body:file.buffer,
    ACL: 'public-read'
  }).promise())

 images.push(file.originalname);

  });

await Promise.all([...resizePromises]);

req.images = images;

next();
};

in other words, i am trying to change my originalname in my req.files to
originalname + "-" + new Date().toISOString() + "-" + uuidv4()

OR

How do i keep the uuid and the date the same in my posts.js and imageResize.js?

来源:https://stackoverflow.com/questions/65475598/how-to-rename-my-originalname-when-using-multer-memorystorage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!