Open In App

File uploading in Node

Improve
Improve
Like Article
Like
Save
Share
Report

File uploading involves a user requesting to upload a file from their client machine to the server. For instance, on platforms like Facebook or Instagram, users upload images, videos, etc. In this article, we’ll explore how to achieve file uploads using Node.js.

Features of Multer module:

The file can be uploaded to the server using the Multer module. There are other modules in the market but multer is very popular regarding file uploading. Multer is a node.js middleware that is used for handling multipart/form-data, which is mostly used as a library for uploading files.

Note: Multer will process only those forms which are multipart (multipart/form-data). So whenever you use multer, make sure you put multipart in form.

Approach to upload file in Node:

  • Module Imports:
    • Import express, path, and multer for server creation, file path operations, and file upload handling.
  • View Engine Configuration:
    • Configure the EJS view engine and set the views directory.
  • Multer Configuration for File Upload:
    • Set up Multer with diskStorage to handle file uploads.
    • Specify the destination folder and filename.
    • Define a maximum file size (1 MB) and a file filter for allowed types (jpeg, jpg, png).
  • Route Setup:
    • Create routes for GET and POST requests.
    • Establish a route for rendering a signup page (GET request).
    • Set up a route for handling file uploads (POST request).
  • Server Initialization:
    • Start the server on port 5000.
    • Handle errors during file upload and respond with success or error messages.

Steps to Setup the Express App:

Step 1: Initialising the Node App:

npm init

Step 2: Installing the required packages

npm install express ejs multer

Project Structure:

Nodeproj

Project Structure

The updated dependencies in package.json file for backend will look like:

"dependencies": {
"express": "^4.18.2",
"ejs": "^3.1.9",
"multer": "^1.4.5-lts.1",
}

The “uploads” folder stores submitted files, while Multer enriches the request object with a `file` or `files` object for uploaded files and a `body` object containing form text field values upon submission.

Example: Below is the code for uploading the file using NodeJs:

Javascript




const express = require("express");
const path = require("path");
const multer = require("multer");
const app = express();
 
// View Engine Setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
 
// var upload = multer({ dest: "Upload_folder_name" })
// If you do not want to use diskStorage then uncomment it
 
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        // Uploads is the Upload_folder_name
        cb(null, "uploads");
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname + "-" + Date.now() + ".jpg");
    },
});
 
// Define the maximum size for uploading
// picture i.e. 1 MB. it is optional
const maxSize = 1 * 1000 * 1000;
 
var upload = multer({
    storage: storage,
    limits: { fileSize: maxSize },
    fileFilter: function (req, file, cb) {
        // Set the filetypes, it is optional
        var filetypes = /jpeg|jpg|png/;
        var mimetype = filetypes.test(file.mimetype);
 
        var extname = filetypes.test(
            path.extname(file.originalname).toLowerCase()
        );
 
        if (mimetype && extname) {
            return cb(null, true);
        }
 
        cb(
            "Error: File upload only supports the " +
                "following filetypes - " +
                filetypes
        );
    },
 
    // mypic is the name of file attribute
}).single("mypic");
 
app.get("/", function (req, res) {
    res.render("Signup");
});
 
app.post("/uploadProfilePicture", function (req, res, next) {
    // Error MiddleWare for multer file upload, so if any
    // error occurs, the image would not be uploaded!
    upload(req, res, function (err) {
        if (err) {
            // ERROR occurred (here it can be occurred due
            // to uploading image of size greater than
            // 1MB or uploading different file type)
            res.send(err);
        } else {
            // SUCCESS, image successfully uploaded
            res.send("Success, Image uploaded!");
        }
    });
});
 
// Take any port number of your choice which
// is not taken by any other process
app.listen(5000, function (error) {
    if (error) throw error;
    console.log("Server created Successfully on PORT 5000");
});


HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>FILE UPLOAD DEMO</title>
</head>
 
<body>
    <h1>Single File Upload Demo</h1>
 
    <form action="/uploadProfilePicture"
    enctype="multipart/form-data" method="POST">
        <span>Upload Profile Picture:</span>
        <input type="file" name="mypic" required/> <br>
        <input type="submit" value="submit">
    </form>
</body>
 
</html>


Steps to run the program:

node index.js

Output:

node18GIF

Output



Last Updated : 18 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads