How to save files to the server using Nodejs

·

4 min read

In This blog, I am gonna talk about how to save files to the server using nodejs. this is something I recently learned when building a project. we do this in middleware.

well if you don't know what is middleware then I'll let you know.

Middleware is software that sits between different components of a computer system or network, acting as a bridge or intermediary between them. It can facilitate communication and data transfer between different applications, services, and systems that may use different protocols, interfaces, or data formats.

Middleware can also provide additional functionality such as security, caching, logging, load balancing, and message routing. It can be used to connect different layers of an application, for example, the presentation layer, business logic layer, and data access layer.

Examples of middleware include web servers, application servers, message brokers, and database middleware. Middleware can be implemented as standalone software, as part of an operating system, or as part of an application framework.

in our case, I am going to use multer to save files coming from the front end to the server.

let's take an example, suppose you are storing user's data in a database and your schema looks similar to this.

const mongoose = require('mongoose');

const schema = mongoose.Schema({
    restaurantId: { type: String },
    items: [{
        name: { type: String, required: true },
        image: { type: String },
        email: { type: String },
        phoneNUmber: { type: String },
    }]
}); 

module.exports = mongoose.model("user", schema);

so, you are going to store the image File on the server and its location inside the database so, when it comes to accessing it back we can do it by setting the location as a route.

for eg., if the image name is 'my-user-1' then your image will be at

http:///localhost:5000/my-user-1.

and for this, you should have this kind of folder structure.

- backend
    - controllers
    - middleware
    - modals
    - routes
    - index.js
    - public/uploads

where the image is going to store at the public/upload path.

hope this, makes sense to you.

now install the package

npm install path multer

once you set up your controllers and models we are going to set middleware to add images to the server.

const express = require("express");
const routes = express.Router();
const { addUser } = require("../controllers/menuController");
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// Set up Multer storage engine
const storage = multer.diskStorage({
    destination: function (req, file, callback) {
        callback(null, path.join('./public/uploads'));
    },
    filename: function (req, file, callback) {
        callback(null, `image-${Date.now()}. ${file.originalname}`);
    }
});

// filter to only allow images as file
const fileFilter = (req, file, callback) => {
    const allowedFileTypes = ["image/jpeg", "image/pjg", "image/png"];
    if (allowedFileTypes.includes(file.mimetype)) {
        callback(null, true);
    } else {
        callback(null, false);
    }
}

// Create Multer middleware
const upload = multer({ storage: storage, fileFilter: fileFilter });

here we have set up disk storage and mentioned the unique name for the file which we are going to receive from the front end also we have added an additional filter to only accept image files in our example but if you want you can allow those files which you wanted.

and finally, we have set up middleware for multer and stored it in the upload variable.

after this, all is required to add middleware in the routes.

// Add error handling middleware for the /addOrUpdate route
routes.post("/add", upload.single('image'), addUser);

here we have added an

-upload.single('image')

as a middleware which means we are only going to save 1 file in 1 request. if we want to deal with multiple files we set something like this

-upload.array('uploadedImages', 10). and this is how we add images to the server using multer as middleware. now there are two important checks also.

  1. how to receive the name of the file in a controller and.

  2. how to send data from the front end.

module.exports.addUser = async (req, res) => {
    const { name, email, phoneNumber } = req.body;
    const { filename } = req.file;

   // business logic
}

here, the filename is the name of the file that is just stored in the server in a recent request and we accessed it by destructuring the req.file.

and when it comes to sending data from the front end you can use formData.

async function sendData() {
    const formData = new FormData();
    formData.append("email", email);
    formData.append("phoneNumber", phoneNumber);
    formData.append("image", image);

    await axios.post('https://api_url.com/', {formData});
}

that's it.

Thank you for reading.