File Uploads With Node.js

In this article, we will learn how to upload a file using Node.js.

Prerequisites:

  • Basic knowledge of Node.js
  • Code editor like Visual Studio 2019

If you’re new in Node.js? You must have to follow the link given below to set up a new Node.js App in Visual Studio.

How To Create Node.js App In Visual Studio

Upload a File in Node.js project

Firstly, we have to install a package to upload a file.

Install the express-fileupload package with the NPM:

Right-click on the npm from Solution Explorer -> Install New npm Packages…

Search and install express-fileupload package.

Open the index.html file from the views folder and add the code in it.

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <form action="fileupload" method="post" encType="multipart/form-data">
        <input type="file" name="profile" accept=".jpeg,.png,.jpg" required>
        <input type="submit">
    </form>
</body>
</html>

Open the index.js file from the routes folder and add the code in it.

'use strict';
var express = require('express');
var router = express.Router();

var fs = require('fs');
var fileupload = require('express-fileupload');

router.use(fileupload());

/* GET home page. */
router.get('/', function (req, res) {
    res.render('index', { title: 'Express' });
});

/* File Upload */
router.post('/fileupload', function (req, res) {

    var file = req.files.profile;

    if (file == undefined || file == null) {
        res.write('<p>No File Chosen !!!</p>');
        res.write('<a href="/">HOME</a>');
        return res.end();
    }

    var directory = './Uploads';
    //Create a directory if it doesn't exist
    if (!fs.existsSync(directory)) {
        fs.mkdirSync(directory);
    }

    if (file.mimetype == 'image/jpeg' || file.mimetype == 'image/png') {
        file.mv("./Uploads/" + file.name, function (error, responseResult) {
            if (error) {
                res.write('<p>Something Went Wrong !!!</p>');
                res.write('<a href="/">HOME</a>');
                return res.end();
            }
            else {
                res.write('<p>File Uploaded Successfully</p>');
                res.write('<a href="/">HOME</a>');
                return res.end();
            }
        });
    }
    else {
        res.write('<p>Only Upload jpg/jpeg/png !!!</p>');
        res.write('<a href="/">HOME</a>');
        return res.end();
    }

});

module.exports = router;

Output:

 

Also, check Binding DropDownList With Database In Node.js

1 Comment

  1. Mokshesh Shah

    Thats nice demo

    I want a demo to image upload on ftp server using nodejs can you please make a small demo for that?

    0
    0
    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories