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:

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series