User Registration with File Upload | Multer Middleware | Express.js

Mritunjay KumarMritunjay Kumar
2 min read

In the Backend using Node js is not a good practice to get the image from the frontend and upload it directly on MongoDB, another 3rd party, or another database. It is good practice to store it temporarily in your server and then use it because in any case comes an error then get the image from temporary files and use it again. If you want to handle the user registration form, some steps follow when the user uploads a file.

Hear the steps to follow for good practice :

1st step is to install the multer and express package in your node js project.

2nd step is to go to the main file or create a file app.js or index.js. And implements this code.

import express from "express";
import multer from "multer";

const app = express();

//Middleware
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./public/temp"); //Location of file where you store the file
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname);
  },
});
const upload = multer({ storage });

//Routes
app.post("/register", upload.fields([{ name: "avatar", maxCount: 1 }]), (req, res) => {
  // Handle user registration here, including uploaded files
console.log(req.files); //Get the file and the where you want

});

If you want to delete the file from the server use this code:-

const filePath = "./path/to/your/file"; //Get the file path from req.files

  fs.unlink(filePath, (err) => {
    if (err) {
      console.error("Error deleting file:", err);
      return;
    }
    console.log("File deleted successfully");
  });
1
Subscribe to my newsletter

Read articles from Mritunjay Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mritunjay Kumar
Mritunjay Kumar