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
Contents
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:
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: grokonez.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": "grokonez.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": "grokonez.com", "license": "ISC", "dependencies": { "express": "^4.16.3", "multer": "^1.3.0" } }
Frontend
Bootstrap views
– Create ./views/index.html file:
Upload MultipartFile %MINIFYHTML77e441db2199cb7246cc65c43edd345616%%MINIFYHTML77e441db2199cb7246cc65c43edd345617%%MINIFYHTML77e441db2199cb7246cc65c43edd345618%%MINIFYHTML77e441db2199cb7246cc65c43edd345619%%MINIFYHTML77e441db2199cb7246cc65c43edd345620%NodeJS/Express - Multer- Upload MultipartFile
– Create ./views/404.html file:
404 Error! %MINIFYHTML77e441db2199cb7246cc65c43edd345623%%MINIFYHTML77e441db2199cb7246cc65c43edd345624%404 Error!
PAGE NOT FOUND
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('
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:
-> Results:
-> Get List Files:
-> Download Files:
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
Last updated on February 6, 2020.
Thanks for help
HI MY FRIEND, THANKYOU FROM ARGENTINA YOU SAVED ME
Thanks for this helpful article but dude I should say this file structure is too bad.