Search code examples
expressfile-uploadmulter

multer file upload - how to get a value from multer in route?


I'm uploading a file using multer with Express.

I'd like access a value from multer's storage object inside the route.
How can I do that?

Multer configuration (right now I only know how to log the key):

const aws = require("aws-sdk");
const multer = require("multer");
const multerS3 = require("multer-s3");

function configureUpload () {
    
  const s3 = new aws.S3({...my credentials...});

  const upload = multer({
    storage: multerS3({
      s3: s3,
      bucket: process.env.S3_BUCKET_NAME,
      metadata: (req, file, cb) => cb(null, { fieldName: file.fieldname }),
      key: (req, file, cb) => {
        const key = `${new Date().toISOString()}-${file.originalname}`;
        return cb(console.log("KEY: ", key), key); // The string I need to access in route
      },
    }),
  });

  return upload;
}

The route:

const express = require("express");
const Person = require("../../../db/models/person");
const configureUpload = require("../../../configureUpload ");

const router = express.Router();

// Saving to MongoDB with mongoose

router.post("/", configureUpload ().any(), async (req, res) => {
  Person.create({
    ...req.body,
    files: [] // I want to add the string in multer.storage.key to this array
  })
  .then((person) => {
    ...
   })
   .catch((err) => {
    ...
   });

});

module.exports = router;

Solution

  • you can simply add req.key = keyValue then you can access in next route using req.key name

    or you can also access req.file or req.files object in route

    In express everything is a middleware so you can easily pass and access in next middleware