In this article, we will learn how to upload a file using Node.js API and Angular 9.
If you’re new in Node.js? You must have to follow the link given below to set up a new Node.js API in Visual Studio.
How To Create Simple Node.js API In Visual Studio
First, create an API in Node.js then call it from Angular 9.
Firstly, we have to install a package to upload a file.
Right-click on the npm from Solution Explorer -> Install New npm Packages…
Search and install express-fileupload package.
Open the index.js file from the routes folder and add the code in it.
'use strict'; var express = require('express'); var router = express.Router(); var fileupload = require('express-fileupload'); var fs = require('fs'); router.use(fileupload()); /* GET home page. */router.post('/fileupload', function (req, res) { if (req.files.photo == undefined || req.files.photo == null) { res.status(415).send(); } const file = req.files.photo; var directory = './Uploads'; //Create a directory if it doesn't exist if (!fs.existsSync(directory)) { fs.mkdirSync(directory); } if (file.mimetype == 'image/jpeg' || file.mimetype == 'image/png') { file.mv("./Uploads/" + file.name, function (error, response) { if (error) { res.status(415).send(); } else { res.status(200).send(); } }); } else { res.status(415).send(); } }); module.exports = router;
Open the app.js file and add the code in it. (To Enable Cross-Origin Requests)
'use strict'; var debug = require('debug'); var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var routes = require('./routes/index'); var users = require('./routes/users'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug'); //Custom : CORS Middleware app.use(function (req, res, next) { //Enabling CORS res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Methods", "*"); res.header("Access-Control-Allow-Headers", "*"); next(); }); // uncomment after placing your favicon in /public //app.use(favicon(__dirname + '/public/favicon.ico')); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', routes); app.use('/users', users); // catch 404 and forward to error handler app.use(function (req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); app.set('port', process.env.PORT || 3000); var server = app.listen(app.get('port'), function () { debug('Express server listening on port ' + server.address().port); });
Open the app.component.html file and add the code in it.
<form (ngSubmit)="onSubmit()"> <input type="file" (change)="handleImage($event.target.files)" accept=".jpeg,.png,.jpg"> <input type="submit"> </form>
Open the app.component.ts file and add the code in it.
import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'FrontEnd'; formData = new FormData(); constructor(private http: HttpClient) { } onSubmit() { return this.http.post('http://localhost:1337/fileupload', this.formData).subscribe( (response) => { alert('File Uploaded Successfully') }, (error) => { alert('Something Went Wrong !!!') } ); } handleImage(files: FileList) { this.formData.delete('photo'); this.formData.append('photo', files[0]); } }
Open the app.module.ts file and add the code in it.
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Output:
Also, check Binding DropDownList With Database In Node.js
In this article, we have to show Create and Used PIPE in angular
In this article, we have to show Create and Used PIPE in angular
In this article, we have to show Create and Used PIPE in angular