Contents hide 1) File Upload In Angular 7 And Node JS 1.1) Create Angular Service 1.2) Create Nodejs Project 1.3) Install Required Packages 1.4) Setup Nodejs (Root File) 1.5) Setup Controller 1.6) Setup Models File Upload In Angular 7 And Node JS Source Code In this tutorial, we will see how to create an app to File Upload In Angular 7 And Node JS. For this we will be using an npm library named as Formidable in NodeJS application. Topics Create Angular Service Create Nodejs Project Install Formidable and Other Packages Setup Nodejs (Root File) Setup Controller Setup Models Create Angular Service letβs first create a service method which will collect the two parameters which both have type File. In my case I am sending two different file i.e Audio and Image, but you can use array of files if you want so. So our service file will be like: app.service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { environment } from 'src/environments/environment'; @Injectable() export class AudioService { HttpUploadOptions = { headers: new HttpHeaders({ Accept: 'application/json' }), }; constructor(private http: HttpClient) {} uploadAudioFiles(Audiofile: File, imageFile: File) { const payload = new FormData(); payload.append('audio', Audiofile); payload.append('image', imageFile); // environment.uploadAudioByFile : Your Rest API EndPoint To Upload Files return this.http .post(environment.uploadAudioByFile, payload, this.HttpUploadOptions) .pipe(map(result => result)); } } So we have created a payload and append an image and audio file as input parameter from arguments which you can set from your any of the component file. Also we have set header as application/json. Now letβs jump to our main concept which is to be implemented in Nodejs application. Create Nodejs Project So first will create a project and install the required package to manage our file upload, so letβs start with creating a new directory. Terminal mkdir node_fileupload cd node_fileupload then init to create Terminal npm init # package name: (node_fileupload) # version: (1.0.0) # description: file upload using node and formidable # entry point: (index.js) index.js # ... this will create a package.json file as a starter file for Package manager Install Required Packages We will install the basic packages like expressjs, body-parser, cors (allow cross origin access) to create our rest server and the final formidable to manage files when its received on server. Terminal npm install -save express body-parser cors formidable and if for development to watch file changes you can install Nodemon Terminal npm install nodemon --save-dev now letβs setup our package.json file in which we will create a script which will run our node application inside script we will create a dev script with the command as mention below: package.json { "name": "node_fileupload", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "", "dev": "PORT=3000 nodemon index.js" /* set process.env.PORT : 3000 */ }, "author": "", "license": "MIT", "dependencies": { "express": "^4.17.0", "body-parser": "^1.19.0", "cors": "^2.8.5", "formidable": "^1.2.1" }, "devDependencies": { "nodemon": "^1.19.0" } } Setup Nodejs (Root File) Setting up the main index.js file which will start and serve our application also we will be setting some parameters and base routes of our application. First of all we will import all the required packages in our index.js file. index.js const express = require('express'); const app = express(); const cors = require('cors'); const bodyParser = require('body-parser'); ... now will configure body parser which will set maximum data set to be received. index.js ... const app = express(); const bodyParser = require('body-parser'); ... // Data Limit app.use(bodyParser.urlencoded({ limit: '50mb', extended: true })); app.use(bodyParser.json({ limit: '50mb' })); body-parser: To handle HTTP POST request in Express.js version 4 and above, you need to install middleware module called body-parser. body-parser extract the entire body portion of an incoming request stream and exposes it on req.body After that we will create a directory named as public which will be static folder and will upload all the files in that directory. Static is for that the node will not use as its part of application as to serve on route. index.js ... const app = express(); ... // static Folders app.use(cors(), express.static('public')); Inside that public folder will create a assets folder in which we will upload our files so when we will access those files the path will not contain /public/ because we declared as a static folder so our URL will be access 127.0.0.1:3000/assets/image.png After that we will create a base path endpoint on which our all api will be expose. index.js ... const app = express(); ... // REST API's app.use('/api', cors(), require('./controllers')); // Will create a controller in some time. and then finally we will create a app listener which will serve our application index.js ... const app = express(); ... // PORT app.listen(process.env.PORT, () => { console.log('Server is runnnig on port ' + process.env.PORT); }); Setup Controller Now Inside our root folder will create a controllers folder and inside that an root file for controller will create an index.js which will manage several routes for your apllication but we just an single route for application. ./controllers/index.js const express = require('express'); const router = express.Router(); router.use('/audio', require('./audio')); // seperate controller for file upload module.exports = router; // export all controllers route to main index.js in root folder Then inside the controllers folder will create an audio.js file which send error or success data in response and we will be using callback function which waits for response. ./controllers/index.js const express = require('express'); const router = express.Router(); const audio = require('../models/audio/uploadAudio'); // Methods to upload file /* @Upload Files Route */ router.post('/uploadAudioByFile', (req, res) => { audio.byFile(req, res, (err, data) => { // @err : Boolean , @data : response Data or message if (err) { res.status(data.statusCode).json(data); // send erroe response with status and err message } else { res.status(data.statusCode).json(data); // send success response with status and data } }); }); module.exports = router; so our Rest API will be http://127.0.0.1:3000/api/audio/uploadAudioByFile Setup Models Now Inside our root folder will create a models folder which will have some methods to handel all the request from the controllers. Inside the models will create another folder named as audio and then inside that we will be create uploadAudio.js files Note: Try to keep the folder structure maintainable so it can be easily understandable to use the methods ./models/audio/uploadAudio.js const formidable = require('formidable'); // import formidable package const form = new formidable.IncomingForm(); const uploadAudio = function() {}; uploadAudio.prototype.byFile = (req, res, callback) => { form.parse(req); // parse the request files /* @fileBegin : Begains to upload files */ form.on('fileBegin', (name, file) => { file.path = `${__dirname}/../../public/assets/${file.name}`; // upload files to the directory }); /* @error : On error We can send resposnse as failed with err message */ form.on('error', err => callback(false, { reason: err, statusCode: 302 })); /* @end: When all the files are uploaded send response as success with success message */ form.on('end', () => { callback(false, { message: `Audio Uploaded Successfully`, statusCode: 200 }); }); }; module.exports = new uploadAudio(); Get More tutorials on NodeJS and Angular 7+ Share this:TwitterFacebookRedditLinkedInWhatsAppPrintTumblr Related Tags: Angular 7, File Upload, formidable, nodejs