Categories
JavaScript Answers

How to store a file with file extension with Node multer?

Spread the love

To store a file with file extension with Node multer, we set the filename property to a function that returns the file name with the extension.

For instance, we write

const multer = require("multer");
const path = require("path");

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "uploads/");
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + path.extname(file.originalname));
  },
});

const upload = multer({ storage });

to set the filename property of the object we call diskStorage with to return the file name by calling cb with path.extname(file.originalname) to include the extension.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *