The Angular 16 and Node.js Express File Upload Example combines the best of both worlds, providing an engaging frontend experience and a powerful backend infrastructure. The result is a beautiful, user-friendly, and secure file-sharing platform that allows users to share their creativity seamlessly.
In this tutorial, you will learn how to handle file uploads using Angular 16 and Node.js with Express.
Prerequisites:
- Node.js installed on your machine.
- Angular CLI installed globally.
- Basic knowledge of TypeScript and Angular.
Angular 16 Node.js Express File Upload Example Tutorial
Steps to create a file upload application in angular and node.js express:
- Part 1: Set up the Node.js Express Server
- Part 2: Set up the Angular Application
- Part 3: Run the Application
Part 1: Set up the Node.js Express Server
Step 1: Create a new project folder and initialize the Node.js package:
mkdir file-upload-example cd file-upload-example npm init -y
Step 2: Install necessary dependencies:
npm install express multer cors --save
Step 3: Create a new file named server.js
in the root directory and set up the Node.js server:
// server.js const express = require('express'); const multer = require('multer'); const cors = require('cors'); const app = express(); const PORT = 3000; // Configure CORS to allow requests from Angular app (adjust the origin to your Angular app's URL) app.use(cors({ origin: 'http://localhost:4200' })); // Configure multer to handle file uploads const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'uploads/'); }, filename: function (req, file, cb) { cb(null, file.originalname); } }); const upload = multer({ storage: storage }); // Define a single route to handle file upload app.post('/upload', upload.single('file'), (req, res) => { if (!req.file) { return res.status(400).json({ message: 'No file uploaded' }); } res.json({ message: 'File uploaded successfully' }); }); app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });
Part 2: Set up the Angular Application
Step 1: Open your cmd and execute the following command to it to install and create a new Angular project using the Angular CLI:
ng new angular-file-upload-example cd angular-file-upload-example
Step 2: Create a file upload component:
ng generate component file-upload
Step 3: Modify the file-upload.component.html
to create a simple file upload form:
<!-- file-upload.component.html --> <div> <h2>Angular Node js File Upload Example</h2> <input type="file" (change)="onFileSelected($event)" /> <button (click)="onUpload()">Upload</button> </div>
Then, Update the app.component.html
file with the following code:
<!-- app.component.html --> <div style="text-align:center"> <h1>Welcome to File Upload Example using Angular and Node js Express!</h1> <app-file-upload></app-file-upload> </div>
Step 4: Update the file-upload.component.ts
to handle the file upload logic:
// file-upload.component.ts import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-file-upload', templateUrl: './file-upload.component.html', styleUrls: ['./file-upload.component.css'] }) export class FileUploadComponent { selectedFile: File | null = null; constructor(private http: HttpClient) { } onFileSelected(event: Event): void { const inputElement = event.target as HTMLInputElement; if (inputElement.files && inputElement.files.length) { this.selectedFile = inputElement.files[0]; } } onUpload(): void { if (!this.selectedFile) { console.log('No file selected'); return; } const formData = new FormData(); formData.append('file', this.selectedFile); this.http.post('http://localhost:3000/upload', formData) .subscribe( (response) => { console.log(response); this.selectedFile = null; }, (error) => { console.error('Error uploading file:', error); } ); } }
Step 5: Update the app.module.ts
to import the necessary modules:
// app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { AppComponent } from './app.component'; import { FileUploadComponent } from './file-upload/file-upload.component'; @NgModule({ declarations: [ AppComponent, FileUploadComponent ], imports: [ BrowserModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Part 3: Run the Application
Step 1: Start the Node.js Express server:
node server.js
Step 2: Run the Angular application:
ng serve
Now, you can access the Angular application in your browser at http://localhost:4200
. The file upload component should be available, and you can use it to select and upload a file. The uploaded files will be saved in the uploads
directory on the server.
Conclusion
In this tutorial, you have learned how to create a simple file upload application using Angular and Node.js Express. And started by setting up the Node.js Express server to handle file uploads using the multer
middleware and enabling CORS to allow requests from the Angular application.
Next, you have learned how to create an Angular component, FileUploadComponent to handle the file selection and upload process. The component used the Angular HttpClient
module to make a POST request to the Node.js server and upload the selected file.