Uploading multiple images with multer to AWS S3

Solution 1:

I managed to get it to work, my problem was my imageResize middleware. I had to implement storage to AWS S3 to the code i had instead of saving it to the disk.

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}));
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();
};