Using multer to transfer variables to next handler

Utilizing multer for image uploads involves a specific configuration. Here is an example of how to set up multer:

import multer from "multer";
import * as mime from "mime-types";
import path from "path";

export const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "uploads/");
  },
  filename: function (req: any, file, cb) {
    const name = path.parse(file.originalname).name + "_" + Date.now();
    const extension = mime.extension(file.mimetype);
    const filename = `${name}.${extension}`;
    
    // req.fileInfo = { filename, name, extension }
    cb(null, filename);
  },
});
export const upload = multer({ storage: storage });

If you wish to access the fileInfo object in the following handler, you can do so like this:

import { upload } from "src/middlewares/imageUpload";

router.post('/imageUpload', upload.single("upload"), async (req, res) => {

// Retrieve the filename from req.fileInfo
const filename = req.fileInfo.filename;

});

In certain cases, storing variables between middleware and handlers may be necessary. While some suggest using res.local, it's important to note that multer's diskStorage configuration does not support the use of the res parameter directly. Attempts to store the fileInfo object in the req sometimes yield inconsistent results, with req.fileInfo being undefined on certain routes despite identical code.

How can one effectively pass the fileInfo object to the subsequent handler?

Answer №1

multer middleware automatically populates the file property on the req object with details about the uploaded file, eliminating the need for manual configuration.

If you prefer to set this information manually, you can attach a fileInfo object to the req object. However, this will only be accessible in subsequent handlers where the multer middleware is present in the pipeline. Therefore, req.fileInfo will remain undefined for routes that bypass the multer middleware.

To ensure consistency, you can route all requests through the multer middleware. In cases where no file is being uploaded, req.fileInfo will still be undefined as multer did not process any file upload.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I cut an array by value in Vue?

I am working on a component that has a list of objects and I need to implement functionality where, when toggled, the objects' title prop is either added to or removed from an array. Adding the value was easy to do, but removing it has proven challeng ...

Enhance CKEditor with Linked Select Boxes Plugin

I have ventured into writing a CKEditor Plugin and have grasped the basic concepts. For instance: CKEDITOR.dialog.add( 'addDocumentGroupDialog', function ( editor ) { return { title: 'Link to a document group', min ...

The magic of coding is in the combination of Javascript

My goal is to create a CSS animation using jQuery where I add a class with a transition of 0s to change the color, and then promptly remove that class so it gradually returns to its original color (with the original transition of 2s). The code below illus ...

The webpage fails to display Vue Bootstrap radio buttons in a filled state

Hey there! I've been working on a project using vuejs and bootstrap-vue-3. My goal is to allow users to print data about the company, so I created a print scss file for that purpose and added some styles. However, I'm facing an issue where the ra ...

Using grid-template-areas in ReactJS function components does not function as expected

REMINDER: Check out and customize the code in CodeSandbox. This is a parent component with 5 children elements. Among them, 3 are React components and the remaining 2 are regular HTML buttons: import "./App.css"; import React from "react&qu ...

Unable to access the 'fn' property of undefined in Handlebars causing a TypeError

I encountered an issue with my custom handlebars helper. When I fail to define values for the parameters, I receive the following error message. module.exports = function(src, color, classatr, options) { if (typeof src === 'undefined') src ...

When the close button on the page is clicked, I want to reset all selectbox values

I want to reset the three select boxes on my page when the close button is clicked, all of which are located within the .popup class. This is the code I am using to clear the fields: clearText: function() { $('.popupBody input').val('& ...

ChaiHttp is a class for the ExpressJS server

Attempting to create some simple tests Presenting my server.js import express from 'express'; export default class Server { constructor(options) { this.port = options.port; this.express = express(); } initialize() { this.con ...

Issue encountered when trying to use Array.sort() method to sort an array of objects

I'm facing an issue sorting an array of objects by a name property present on each object. When utilizing the sort() method with the given code snippet, I encounter the following error: ERROR ReferenceError: b is not defined This is my code block: m ...

Tips on updating a child object in the state using a reducer with Redux

I am facing a challenge with modifying elements inside an object within my state. Currently, I am able to modify elements at the first level, such as the step property. However, I am seeking a solution to modify elements within an object nested inside my s ...

Is it possible to upload a file to my web application without having configured any backend system?

Currently, I am in the process of developing a landing page that includes a form where users can input their data and send an email. I have successfully implemented the form using HTML, CSS, and JavaScript, and I have even managed to incorporate the email- ...

What is the best way to create a form with two inputs that redirects me to a different page based on the inputs chosen?

Seeking assistance to resolve a challenging problem that I am currently facing. Any suggestions on the technology or backend skills needed for this task would be greatly appreciated, as well as any advice that can help me progress in the right direction. ...

Mastering the Art of Concise Writing: Tips to

Is there a way to write more concisely, maybe even in a single line? this.xxx = smt.filter(item => item.Id === this.smtStatus.ONE); this.yyy = smt.filter(item => item.Id === this.smtStatus.TWO); this.zzz = smt.filter(item => item.Id == ...

Creating a promise class in JavaScript

I am in the process of creating a simple promise class with chainable .then() functionality in javascript. Here is my progress so far: class APromise { constructor(Fn) { this.value = null; Fn(resolved => { this.value = resolved; }); ...

Having trouble retrieving a remote JSON link from a local HTML file in Google Chrome

Having trouble fetching a JSON from the following link: [https://www.nseindia.com/api/equity-stockIndices?index=NIFTY%2050]. When accessed through a browser, the JSON is displayed on screen as expected. However, attempting to fetch this link from JavaScrip ...

What is the best way to enable autocomplete in vscode when using a function in TypeScript that returns a union type?

Is there a way to improve editor autocomplete when calling a function that returns a union type? For instance, in the given code snippet, after invoking getProperty<ColorfulOrCircle>() (line 14), the variable b should display the accessible properti ...

Concealing error messages in Node.js and Express when handling POST requests

My Restful API Server is built on Node.js using Express.js. Recently, I noticed that sensitive information about my source code, such as directory paths, can be accessed by sending a Curl request like curl -X POST ~. An example of the error message I enc ...

Creating a JavaScript function triggered by a click event that will redirect to

I'm attempting to create an onclick function that will redirect you to a new page when you click on a div element, much like the A + href attribute in HTML. Any suggestions on how to achieve this? Should I just add an A tag inside the div? I'm un ...

Sweetalert seems to have hit a roadblock and is not functioning properly. An error has been detected in its TS file

Currently, I am responsible for maintaining an application that utilizes Angular 7.0.7 and Node 10.20.1. Everything was running smoothly until yesterday when my PC unexpectedly restarted. Upon trying to run ng serve, I encountered the following error: E ...

"Losing focus: The challenge of maintaining focus on dynamic input fields in Angular 2

I am currently designing a dynamic form where each Field contains a list of values, with each value represented as a string. export class Field { name: string; values: string[] = []; fieldType: string; constructor(fieldType: string) { this ...