DEV Community

Cover image for Upload image files with Multer
Collins Mutai
Collins Mutai

Posted on

1

Upload image files with Multer

Multer is a nodejs middleware for uploading files in a nodejs application (Express Multer Middleware, n.d.).
To use multer install the package using

npm install multer
Enter fullscreen mode Exit fullscreen mode

Once it is installed, import the package using this command

const multer = require("multer")
Enter fullscreen mode Exit fullscreen mode

Next is configuring the files' storage destination and preferred filenames. A callback function is used to create the filenames for each of the file uploads.

const storage = multer.diskStorage({
  destination: "./images",
  filename: (req, file, cb) => {
    return cb(
      null,
      `${file.fieldname}_${Date.now()}`
    );
  },
});
Enter fullscreen mode Exit fullscreen mode

After configuring the storage location and the filename, add the storage object to a multer instance.

const upload = multer({ storage: storage });
Enter fullscreen mode Exit fullscreen mode

The middleware is then added to the request to process any incoming file from the request body. A post request to the route "/upload" will upload a single image file from a multi-part form field named product and save it inside a folder called images.

app.post("/upload", upload.single("product"), (req, res) => {
  res.json({
  file_info: req.file,
});
Enter fullscreen mode Exit fullscreen mode

To access the file details, we can use the output of the res.file object and return it in json format.

{
  "file_info": {
    "fieldname": "product",
    "originalname": "img3.jpeg",
    "encoding": "7bit",
    "mimetype": "image/jpeg",
    "destination": "./upload/images",
    "filename": "1706247839665_img3.jpeg",
    "path": "upload/images/1706247839665_img3.jpeg",
    "size": 107421
  }
}
Enter fullscreen mode Exit fullscreen mode

This is an easy way to upload files in a nodejs application. With more configurations, you can specify the required file types and so on.
Credits:

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

đź‘‹ Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay