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
Once it is installed, import the package using this command
const multer = require("multer")
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()}` ); }, });
After configuring the storage location and the filename, add the storage object to a multer instance.
const upload = multer({ storage: storage });
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, });
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 } }
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:
GreatStack. (2024, January 2). How to create full stack E-Commerce website using React JS, MongoDB, Express & Node JS 2024 [Video]. YouTube. https://www.youtube.com/watch?v=y99YgaQjgx4
Express multer middleware. (n.d.). https://expressjs.com/en/resources/middleware/multer.html
Top comments (0)