NodeJS/Express – Upload/Download MultipartFiles/Images – Multer + JQuery Ajax + Bootstrap

In the tutorial, we show how to build a NodeJS/Express web-application to upload MultipartFile-s/Images by Multer middleware, JQuery Ajax and Bootstrap view.

Related posts:
Multer – Build RestAPI to upload a MultipartFile to NodeJS/Express
Integrate NodeJS/Express – JQuery Ajax POST/GET – Bootstrap view example
NodeJS/Express – Upload Text-Fields + MultipartFile with Multer, Jquery Ajax, Bootstrap 4

Goal

Prerequisites

Multer – Build RestAPI to upload a MultipartFile to NodeJS/Express
Integrate NodeJS/Express – JQuery Ajax POST/GET – Bootstrap view example

Objective

In the tutorial, we build a NodeJS/Express web-application that uses Multer middleware to upload/download MultipartFiles/Images using JQuery Ajax & Bootstrap view.

Project structure:


/NodeJS-Express-Multer-MultipartFile-Ajax-JQuery-Bootstrap
	/app
		/config
			multer.config.js
		/controllers
			file.controller.js
		/routers
			file.router.js
	/node_modules
	/resources
		/static
			/js
				getrequest.js
				postrequest.js
	/uploads
		/*contains the uploaded-files*/
	/views
		index.html
		404.html
	package.json
	package-lock.json
	server.js

-> results:

NodeJS-Express-Multer-Upload-MultipartFile-Ajax-Jquery-Bootstrap-dowloadfiles

Practice

Setting up NodeJS/Express project

Create a folder NodeJS-Express-Multer-MultipartFile-Ajax-JQuery-Bootstrap:


mkdir NodeJS-Express-Multer-MultipartFile-Ajax-JQuery-Bootstrap
cd NodeJS-Express-Multer-MultipartFile-Ajax-JQuery-Bootstrap

Then init NodeJS project:


NodeJS-Express-Multer-MultipartFile-Ajax-JQuery-Bootstrap>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install ` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (nodejs-express-multer-multipartfile-ajax-jquery-bootstrap)
version: (1.0.0)
description: Building a NodeJS/Express web-application that uses Multer middleware to upload MultipartFile with Ajax-JQuery & Bootstrap view
entry point: (index.js) server.js
test command:
git repository:
keywords: NodeJS, Express, Multer, Bootstrap, Ajax-Jquery
author: ozenero.com
license: (ISC)
About to write to C:\nodejs\NodeJS-Express-Multer-MultipartFile-Ajax-JQuery-Bootstrap\package.json:

{
  "name": "nodejs-express-multer-multipartfile-ajax-jquery-bootstrap",
  "version": "1.0.0",
  "description": "Building a NodeJS/Express web-application that uses Multer middleware to upload MultipartFile with Ajax-JQuery & Bootstrap view",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "NodeJS",
    "Express",
    "Multer",
    "Bootstrap",
    "Ajax-Jquery"
  ],
  "author": "ozenero.com",
  "license": "ISC"
}


Is this ok? (yes) yes

-> Install Express, Multer:


npm install express multer --save

-> see package.json file:


{
  "name": "nodejs-express-multer-multipartfile-ajax-jquery-bootstrap",
  "version": "1.0.0",
  "description": "Building a NodeJS/Express web-application that uses Multer middleware to upload MultipartFile with Ajax-JQuery & Bootstrap view",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "NodeJS",
    "Express",
    "Multer",
    "Bootstrap",
    "Ajax-Jquery"
  ],
  "author": "ozenero.com",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.3",
    "multer": "^1.3.0"
  }
}

Frontend

Bootstrap views

– Create ./views/index.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Upload MultipartFile</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
	<script src="/static/js/postrequest.js"></script>
	<script src="/static/js/getrequest.js"></script>
</head>
 
<body>
	<div class="container">
		<h3>NodeJS/Express - Multer- Upload MultipartFile</h3>
		<form class="form-horizontal" method="POST" enctype="multipart/form-data" id="fileUploadForm">
			<div class="form-group">
				<label class="control-label col-sm-2" for="uploadfile">Upload File:</label>
				<div class="col-sm-5">
					<input type="file" class="form-control" id="uploadfile" placeholder="Upload File"  name="uploadfile"></input>
				</div>
			</div>
			<div class="form-group"> 
			    <div class="col-sm-offset-2 col-sm-5">
			      <button type="submit" class="btn btn-default" id="btnSubmit">Upload</button>
			      <button type="button" class="btn btn-default" id="btnGetFiles">Files</button>
			    </div>
			</div>
		</form>
		<hr/>
		<div class="col-sm-offset-2" id="listFiles">
		</div>
	</div>
</body>
</html>

– Create ./views/404.html file:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>404 Error!</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
  
<div class="jumbotron text-center">
  <h1>404 Error!</h1>
  <p>PAGE NOT FOUND</p>
</div>
</body>
</html>

Jquery Ajax

– Create a JQuery Ajax POST multipart/form-data form, see ./resources/static/js/postrequest.js file:


$(document).ready( () => {
    $("#btnSubmit").click((event) => {
        //stop submit the form, we will post it manually.
        event.preventDefault();
        doAjax();
    });
 
});
 
function doAjax() {
 
    // Get form
    var form = $('#fileUploadForm')[0];
    var data = new FormData(form);
 
    $.ajax({
        type: "POST",
        enctype: 'multipart/form-data',
        url: "/api/files/upload",
        data: data,
        processData: false, //prevent jQuery from automatically transforming the data into a query string
        contentType: false,
        cache: false,
        success: (data) => {
            $("#listFiles").text(data);
        },
        error: (e) => {
            $("#listFiles").text(e.responseText);
        }
    });
}

– Create a Jquery Ajax GET, see ./resources/static/js/getrequest.js file:


$( document ).ready( () => {
	
	var url = window.location;
	
	// GET REQUEST
	$("#btnGetFiles").click( (event) => {
		event.preventDefault();
		ajaxGet();
	});
	
	// DO GET
	function ajaxGet(){
		$.ajax({
			type : "GET",
			url : "/api/files/getall",
			success: (data) => {
				//clear old data
				$("#listFiles").html("");
				
				/*
					render list of files
				*/
				$("#listFiles").append('
    '); $.each(data, (index, filename) => { $("#listFiles").append('
  • ' + filename + '
  • '); }); $("#listFiles").append('
'); }, error : (err) => { $("#listFiles").html(err.responseText); } }); } })

Backend

Config Multer Upload

– Create ./app/config/multer.config.js file:


const multer = require('multer');

var storage = multer.diskStorage({
	destination: (req, file, cb) => {
	  cb(null, __basedir + '/uploads/')
	},
	filename: (req, file, cb) => {
	  cb(null, file.originalname)
	}
});

var upload = multer({storage: storage});

module.exports = upload;

Express Routers

– Create ./app/routers/file.router.js file:


module.exports = (app, router, upload) => {
    const fileWorker = require('../controllers/file.controller.js');
	
	var path = __basedir + '/views/';
	
	router.use((req,res,next) => {
		console.log("/" + req.method);
		next();
	});
	
	app.get('/', (req,res) => {
		res.sendFile(path + "index.html");
	});
	
	app.post('/api/files/upload', upload.single("uploadfile"), fileWorker.uploadFile);
	
	app.get('/api/files/getall', fileWorker.listAllFiles);
	
	app.get('/api/files/:filename', fileWorker.downloadFile);

	app.use('/',router);
 
	app.use('*', (req,res) => {
		res.sendFile(path + "404.html");
	});
}

File Controllers

– Create ./app/controllers/file.controller.js file:


const uploadFolder = __basedir + '/uploads/';
const fs = require('fs');

exports.uploadFile = (req, res) => {
	res.send('File uploaded successfully! -> filename = ' + req.file.filename);
}

exports.listAllFiles = (req, res) => {
	fs.readdir(uploadFolder, (err, files) => {
		res.send(files);
	})
}

exports.downloadFile = (req, res) => {
	var filename = req.params.filename;
	res.download(uploadFolder + filename);  
}

Server.js

Implement ./server.js file:


var express = require('express');
var app = express();
var router = express.Router();
var upload = require('./app/config/multer.config.js');
 
global.__basedir = __dirname;

app.use(express.static('resources'));

require('./app/routers/file.router.js')(app, router, upload);
 
// Create a Server
var server = app.listen(8081, () => {
 
  var host = server.address().address
  var port = server.address().port
 
  console.log("App listening at http://%s:%s", host, port); 
})

Run & check results

Start NodeJS server:

node server.js
App listening at http://:::8081

-> Upload Files:

NodeJS-Express-Multer-Upload-MultipartFile-Ajax-Jquery-Bootstrap-uploadfile

NodeJS-Express-Multer-Upload-MultipartFile-Ajax-Jquery-Bootstrap-uploadfile-request

-> Results:

NodeJS-Express-Multer-Upload-MultipartFile-Ajax-Jquery-Bootstrap-all-upload-files

-> Get List Files:

NodeJS-Express-Multer-Upload-MultipartFile-Ajax-Jquery-Bootstrap-list all files

NodeJS-Express-Multer-Upload-MultipartFile-Ajax-Jquery-Bootstrap-getallfiles-request

-> Download Files:

NodeJS-Express-Multer-Upload-MultipartFile-Ajax-Jquery-Bootstrap-dowloadfiles

NodeJS-Express-Multer-Upload-MultipartFile-Ajax-Jquery-Bootstrap-download-file-request

Sourcecode

To run below sourcecode, follow the guides:


step 0: download & extract zip file -> we have a folder ‘NodeJS-Express-Multer-MultipartFile-Ajax-JQuery-Bootstrap’
step 1: cd NodeJS-Express-Multer-MultipartFile-Ajax-JQuery-Bootstrap
step 2: npm install express multer -–save
step 3: node server.js
step 4: makes a POST request: http://localhost:8081

-> Sourcecode:

NodeJS-Express-Multer-MultipartFile-Ajax-JQuery-Bootstrap

4 thoughts on “NodeJS/Express – Upload/Download MultipartFiles/Images – Multer + JQuery Ajax + Bootstrap”

Leave a Reply

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