Nodejs Course

- Screenshots
- In brief about upload.js and Usage

There is a good module for working with file uploads, called "Multer".
Based on Multer module, i made a JavaScript class to easily upload files with node.js, with a minimum necessary code.
This class, called uploadFile is exported as a module, and can be included with require().

Create a Node.js module to upload file with Multer

• You can create the files with the code presented in this page, or ..:
- Click this link to download the whole script: Node.js Simple Upload Files.

1. First, we have to install the Express and Multer modules with NPM (Node.js Package Manager).
Open the command line interface and tell NPM to download these packages.
npm install --save express

npm install --save multer
2. Lets create our module that uses multer to upload files, with options to set allowed file extensions and maximum file size for upload.
In the directory of your Node.js project create a file called "upload.js", and add this code (click on the code to select it):
//uploads file to server with multer module
class uploadFile {
  //set needed properties
    this.multer = require('multer');
    this.destination = null;
    this.exts =['bmp', 'doc', 'flv', 'gif', 'jpg', 'jpe', 'json', 'mp3', 'mp4', 'pdf', 'png', 'txt']; //allowed extensions
    this.maxsize =3; //maximum allowed file size; in MB
    this.rewrite = true; //true=rewrite the file if exists; false=sets the file name: ''

/*Sets properties, receives object:
  destination: 'folder for uploaded file' (Required, default: null)
  exts: [array with allowed extensions] (Optional, default: ['bmp', 'doc', 'flv', 'gif', 'jpg', 'jpe', 'json', 'mp3', 'mp4', 'pdf', 'png', 'txt'])
  maxsize: integer number for maximum allowed file size, in MB (Optional, default: 3)
  rewrite: true or false (Optional, default: true); true=rewrite the file if exists; false=sets the file name: 'originalname-timestamp'
  set setProp(o){
    if(o.destination) this.destination = o.destination;
    if(o.exts) this.exts = o.exts;
    if(o.maxsize) this.maxsize = o.maxsize*1;
    if(o.rewrite) this.rewrite = o.rewrite;

  //set main multer objects for upload
    //sets destination folder and file name
    var storage = this.multer.diskStorage({
      destination: (req, file, cb)=>{
        cb(null, this.destination);
      filename: (req, file, cb)=>{
        this.er_ext ='No valid extension.\n Allowed extensions: '+ this.exts.join(', ');
        //check extension
        var ext = file.originalname.match(/\.([A-z0-9]+)$/i);
        if(ext && ext[1]){
          ext = ext[1];
          for(var i=0; i<this.exts.length; i++){
              this.er_ext ='';

        //if no error, sets destination file name
          if(this.rewrite ===true) var fname = file.originalname;
          else var fname = file.originalname.replace('.'+ext, '-''.'+ext);
          cb(null, fname);
        else return cb(new Error(this.er_ext), false);
    //Acepts a single file with the name 'up_f'. This file will be stored in req.file
    this.upload = this.multer({storage: storage, limits:{ fileSize: this.maxsize*1024*1024 }}).single('up_f');


  //Posting the file upload; Receives - req=request, res=response, cb=callback function
  //Returns an object in the callback function, with file data, or {err:'error message'} in case of error
  post(req, res, cb){
    if(this.destination ==null) return cb({err:"Set a destination folder for upload, with: dirUpload \n Example:\n upload.dirUpload = __dirname+'/uploads'"});
    else {
      // req.file is the `avatar` file; req.body will hold the text fields, if there were any 
      this.upload(req, res, (err)=>{
          if(this.er_ext !='') var re ={err:this.er_ext};
          else if(err.code =='LIMIT_FILE_SIZE') var re ={err:'File to large, maximum allowed size: '+ this.maxsize +' MB'};
          else var re ={err:err};
        else {
          var re = req.file;
          console.log('File Uploaded');

        return cb(re);

//assign object of uploadFile class to module.exports
module.exports = new uploadFile();
3. Now we create a ".htm" file with the upload form and Ajax code that performs the upload without loading page.
Save the following code in a file called "form.htm", in the directory of your Node.js project:
<!doctype html>
<html lang="en">
<meta charset="utf-8" />
<title>Node.js Upload Files</title>
<h1>Node.js Upload Files</h1>
<pre id="resp">Here it shows server response</pre>
<form id="uploadf" enctype="multipart/form-data" action="/upload" method="post">
 <input type="file" name="up_f" id="up_f" />
 <input type="submit" value="Upload" name="submit" />
var resp = document.getElementById('resp');
var form = document.getElementById('uploadf'); //get the form

//sends form data with ajax to server
function sendFile(ev){

  //get the form and send its data to server
  var data = new FormData(form);
  var req = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');'post', form.action, true);

  //receives and parse response in JSON format
    if(req.readyState ==4){
      var obr = JSON.parse(req.responseText.replace(/\\\\/g, '/'));
        //HERE you can parse the obr JSON object

        if(obr.err) resp.innerHTML ='<h4 style="color:#ee0000">'+JSON.stringify(obr.err, null, 2).replace(/(^")|("$)/g, '').replace(/\\n/ig, '<br>')+'</h4>';
        else resp.innerHTML = JSON.stringify(obr, null, 2);
  return false;

// calls sendFile() on submit
form.addEventListener('submit', sendFile, false);
- The JavaScript code in the "form.htm" file sends the form to server, and displays the response in web page.

4. Now, we create a "server.js" file that uses Express to serv the pages to browser, and the "upload.js" module to upload the file when form data is sent.
Copy and save the following code in a "server.js" file in the same directory:
const express = require('express');
const upload = require('./upload.js');
const port =8080;
const app = express();
app.set('port', port); 

//Showing form.htm file on homepage
app.get('/', (req, res)=>{

Before, calls setProp() passing an object, to set destination folder (here 'uploads'), and other properties
Full object:
  destination: 'folder for uploaded file' (Required, default: null)
  exts: [array with allowed extensions] (Optional, default: ['bmp', 'doc', 'flv', 'gif', 'jpg', 'jpe', 'json', 'mp3', 'mp4', 'pdf', 'png', 'txt'])
  maxsize: integer number for maximum allowed file size, in MB (Optional, default: 3); 0.5 = 500 KB
  rewrite: true or false (Optional, default: true); true=rewrite the file if exists; false=sets the file name: ''
upload.setProp ={destination: __dirname+'/uploads', exts:['jpg', 'png', 'mp3'], maxsize:0.5};

//calls when POST request'/upload', (req, res)=>{
 //passes a callback function that receives an object with response: data of the uploaded file, or {err:'error message'} in case of error, res, (re)=>{
    //HERE you can parse the received object

    //outputs the object response as a JSON string

var server = app.listen(port, ()=>{
  console.log('Listening on port ' + server.address().port);
- Run the "server.js" in command line interface.
node test/server.js
Access the server in your browser, on port 8080 ( //localhost:8080/ ).
- Now you can upload files on your server with Node.js.

• After the file is uploaded, the post() method of the "upload.js" module returns an object with file data in a callback function received as argument:
  "fieldname": "up_f",
  "originalname": "dolphin.jpg",
  "encoding": "7bit",
  "mimetype": "image/jpeg",
  "destination": "e:/nodejs/test_upload/uploads",
  "filename": "dolphin.jpg",
  "path": "e:/nodejs/test_upload/uploads/dolphin.jpg",
  "size": 3752
- or an object with error message in case of error: "{err:'error message'}"


The files for Node.js server and upload module, in a "test" directory:
Node.js upload test project

Object response with data of the uploaded file:
Node.js response upload file

Message in case of error:
Node.js upload test project

In brief about upload.js and Usage

upload.js is a module that simplifies the code for upload files in node.js projects. It is based on the Multer module.

- To download the script, click: Node.js Simple Upload Files


1. Install the multer module with NPM from command line interface:
npm install --save multer
2. Copy "upload.js" and "form.htm" directly in your project directory.
3. Include "upload.js" in the Node.js server file:
const = require('./upload.js');
4. Set destination of the directory for upload files, with upload.setProp :
upload.setProp ={destination: __dirname+'/uploads'};
- Additionally, you can set other properties too: "exts", "maxsize", "rewrite" (see the comments in the upload.js file).

5. Show "form.htm" file on browser. Example with Express:
6. Call the method when POST request with form data:, res, callback);
"callback" is a callback function with an argument in which receives an object response from post() method.

- More important:
Have a Good life with everyone and with yourself.

Daily Test with Code Example

Which tag adds a new line into a paragraph?
<b> <br> <p>
First line ...<br>
Other line...
Which CSS property can be used to add space between letters?
text-size word-spacing letter-spacing
#id {
  letter-spacing: 2px;
What JavaScript function can be used to get access to HTML element with a specified ID?
getElementById() getElementsByTagName() createElement()
var elm = document.getElementById("theID");
var content = elm.innerHTML;
Click on the "echo" correct instruction.
echo "" echo ""; echo """;
echo "Address URL:";
Upload Files with Express and Multer

Last accessed pages

  1. Get Mime Type of file or string content in PHP (6148)
  2. Disable button and Enable it after specified time (17416)
  3. Working with HTML attributes in PHP (13578)
  4. Redirects (4874)
  5. Get Duration of Audio /Video file before Upload (15355)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (270)
  2. Read Excel file data in PHP - PhpExcelReader (63)
  3. The Mastery of Love (59)
  4. PHP Unzipper - Extract Zip, Rar Archives (58)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (42)