'Reading the buffer property of each uploaded file, when there are multiple

I am trying to upload multiple files to my server using multer. Even though I can read the req.files array, but can't access the buffer property of them. I tried console.logging them, which only results in undefined.

This is my html (ejs) code:

<form method="post" action="/send" enctype="multipart/form-data">
    <div class="row">
        <div class="col">
            <input type="file" multiple class="form-control" name="files" />
        </div>
        <div class="col text-end">
            <input type="submit" class="btn btn-primary w-100" />
        </div>
    </div>
</form>

The route:

const express = require("express");
const router = express.Router();

const multer = require("multer");
const upload = multer({ dest: "uploads/" });

const indexController = require("../controllers/index.controller");

router.post("/send", upload.array("files", 5), indexController.send);

module.exports = router;

... the controller:

exports.send = async (req, res) => {
    ...
    console.log(req.files); // [ { fieldname: 'files', ..., size: 1576 } ]
    console.log(req.files.map((f) => f.buffer)); // [ undefined ]
    ...
}

How do I read the .buffer property of each file, when there are multiple? Any help is appreciated.



Solution 1:[1]

I am using memoryStorage and still cant figure this out. I wont get the buffer file in the Multers filter option, only at the controllers level. I tried this code but I only get these fields (no buffer)

// RESPONSE (buffer is missing)

{
    fieldname: 'formImages',
    originalname: 'file-test.jpeg',
    encoding: '7bit',
    mimetype: 'image/jpeg'
}

// CODE:

const multer = require("multer");
const sharp = require("sharp");
const sharpFilter = async (req, file, cb) => {
  const locationPath = `${process.env.UPLOAD_FOLDER + "/" + file.originalname}`;
  await sharp(file)
    .resize({
      width: 2000,
      height: 2000,
      fit: "cover",
    })
    .toFile(locationPath);
  cb(null, true);
};

exports.upload = multer({
  storage: multer.memoryStorage(),
  fileFilter: sharpFilter,
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tyler2P