DEV Community

Cover image for Upload files to server using Node.js ejs template and Multer package
Pankaj Kumar
Pankaj Kumar

Posted on • Updated on

Upload files to server using Node.js ejs template and Multer package

In this article we will understand to upload files in nodejs using express + multer package + ejs template.

At first create server.js

In this article we will understand to upload file in nodejs using express+multer+ejs template


let express = require("express"),
    ejs = require('ejs'),
    app = express(),
    path = require('path'),
    multer = require('multer');

   app.set('view engine', 'ejs'); // code to set the ejs for rendering template

let storage = multer.diskStorage({
    destination: function(req, file, callback) {
        callback(null, './uploads')
    },
    filename: function(req, file, callback) {
        console.log(file)
        callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
    }
   })

   app.get('/api/file', function(req, res) {
    res.render('index')
   })

  app.post('/api/file', function(req, res) {
    let upload = multer({
        storage: storage,
        fileFilter: function(req, file, callback) {
            let ext = path.extname(file.originalname)
            if (ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') {
                return callback(res.end('Only images are allowed'), null)
            }
            callback(null, true)
        }
    }).single('userFile');
    upload(req, res, function(err) {
        res.end('File is uploaded')
    })
  })
   let port = process.env.PORT || 3000
   app.listen(port, function() {
    console.log('Node.js listening on port ' + port);
   })

Enter fullscreen mode Exit fullscreen mode

In the above file, at the top we have created an app with express framework, below that we have included multer package for uploading task at server end. Below that we have set the uploading location of files and renaming of files.

Now we have create a get method with route '/api/file' which simply renders the form field. And on the post method with the same name we perform the actual task of file uploading using nodejs multer package.

Now let's see the code at client end:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <form id="uploadForm" enctype="multipart/form-data" method="post">
        <input type="file" name="userFile" />
        <input type="submit" value="Upload File" name="submit">
    </form>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

In the above frontend part, we have simply a html page where we have a form having a file of input type file and a submit button. Download the zipped code for fully functional code.

Hope this was helpful to you! Thanks alot.

This article is originally posted over jsonworld

Top comments (0)