Create a single file uploading system using Multer, Express and Node

Create a single file uploading system using Multer, Express and Node

In this tutorial, we are going to create a single file uploading system using Multer, Express.js, and Node.js. This tutorial is best suitable for beginners who are just getting started

To know more about Multer middleware methods, read the official documentation here.

Multer is a middleware for handling multipart/form-data, extremely useful for managing file uploads. We will use Express.js middleware framework to build the single file upload system along with Multer and Node.js.

Set up Node App for Single File Uploading Tutorial

Run command and hit enter to create app folder:

mkdir multer-file-upload && cd multer-file-upload

Generate exclusive package.json file

npm init

Install required NPM packages:

npm install multer express cors body-parser

Create app.js to store server settings for Multer file uploading system:

touch app.js

Once all these packages installed, these are registered inside the package.json file:

{
 "name": "multer-single-file-upload",
 "version": "1.0.0",
 "description": "",
 "main": "app.js",
 "scripts": {
   "test": "echo \"Error: no test specified\" && exit 1"
 },
 "author": "Digamber Rawat",
 "license": "ISC",
 "dependencies": {
   "body-parser": "^1.19.0",
   "cors": "^2.8.5",
   "express": "^4.17.1",
   "multer": "^1.4.2"
 }
}

Multer Single File Upload Tutorial

In the main app.js file, we will import the following NPM packages: express, path, cors, multer and bodyParser.

const express = require('express');
const path = require('path');
const cors = require('cors');
const multer = require('multer');
const bodyParser = require('body-parser');

Run below command to create public folder in the root of the project directory, here we will store the uploaded files:

mkdir public

Define `public` folder path in app.js file.

const PATH = './public/';

Define multer.diskStorage({ }) method and pass destination and filename middleware functions inside of it as mentioned below.

const storage = multer.diskStorage({
 destination: (req, file, cb) => {
   cb(null, DIR);
 },
 filename: (req, file, cb) => {
   const fileName = file.originalname.toLowerCase().split(' ').join('-');
   cb(null, fileName)
 }
});

Then, we will validate file types such as: .jpeg, .jpg, .png and .gif in Multer single file upload system using fileFilter and file.mimetype options.

const upload = multer({
   storage: storage,
   fileFilter: (req, file, cb) => {
       if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg" || file.mimetype == "image/gif") {
           cb(null, true);
       } else {
           cb(null, false);
           return cb(new Error('Allowed only .png, .jpg, .jpeg and .gif'));
       }
   }
});

This method will validate files during file upload in node.js app if the file type is relevant then it will store the file in `public` folder else throw the error.

Final output:

const express = require('express');
const path = require('path');
const cors = require('cors');
const multer = require('multer');
const bodyParser = require('body-parser');


const PATH = './public/';

const storage = multer.diskStorage({    destination: (req, file, cb) => {        cb(null, DIR);    },    filename: (req, file, cb) => {        const fileName = file.originalname.toLowerCase().split(' ').join('-');        cb(null, fileName)    } });

const upload = multer({    storage: storage,    fileFilter: (req, file, cb) => {        if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg" || file.mimetype == "image/gif") {            cb(null, true);        } else {            cb(null, false);            return cb(new Error('Allowed only .png, .jpg, .jpeg and .gif'));        }    } });

app.post('/add', upload.single('image'), (req, res, next) => {    const user = new User({        _id: new mongoose.Types.ObjectId(),        name: req.body.name,        imageURL: req.file.path    });    user.save().then(result => {        res.status(201).json({            message: "User registered successfully!",        })    }) })

app.listen(3000, function () {    console.log("Working on port 4000"); });

Conclusion

Finally, we have completed the single file upload tutorial using Multer/Express and Node.js. I hope you loved this tutorial, please consider it sharing with others.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

The Complete Node.js Developer Course (3rd Edition)

Angular & NodeJS - The MEAN Stack Guide

NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

Best 50 Nodejs interview questions from Beginners to Advanced in 2019

Node.js 12: The future of server-side JavaScript

An Introduction to Node.js Design Patterns

Basic Server Side Rendering with Vue.js and Express

Fullstack Vue App with MongoDB, Express.js and Node.js

How to create a full stack React/Express/MongoDB app using Docker

Creating your first npm package


node-js express web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Node.JS Developers | Skenix Infotech

We are providing robust Node.JS Development Services with expert Node.js Developers. Get affordable Node.JS Web Development services from Skenix Infotech.

How to Hire Node.js Developers And How Much Does It Cost?

A Guide to Hire Node.js Developers who can help you create fast and efficient web applications. Also, know how much does it cost to hire Node.js Developers.

Top Node.js Development Companies and Expert NodeJS Developers

A thoroughly researched list of top NodeJS development companies with ratings & reviews to help hire the best Node.JS developers who provide development services and solutions across the world. List of Leading Node.js development Service Providers...

Hire Web Developer

Looking for an attractive & user-friendly web developer? HourlyDeveloper.io, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...

Hire Node JS Developer from Expert Node JS Development Company

NodeJS Development Company-Hire Node JS developer from the most prominent NodeJS development company, Mobiweb and get remarkable Node.js app development services.