Angular 16 Node JS File Upload Example

Angular 16 + Node Express file/image upload with form data example; Through this tutorial, i am going to show you how to upload file/image in Angular 16 app with node express js as backend.

Angular 16 Node JS File Upload Example

Follow the below given steps to upload files using node js (as backend) + Angular 16 (as frontend) apps; as follows:

  • Create Angular Frontend App
    • Step 1 – Create New Angular App
    • Step 2 – Install ng-file-upload Directive & toastr Notification
    • Step 3 – Import Installed Modules on app.module.ts
    • Step 4 – Create File Upload Form
    • Step 5 – Import Components app.component.ts
  • Create Node Express JS Backend
    • Step 1 – Create Node JS App
    • Step 2 – Install Express body parser and cors Dependencies
    • Step 3 – Create Server.js
    • Step 4 – Start Node JS App

Create Angular Frontend App

Follow the below given steps to create angular app for file uploads, as frontend;

Step 1 – Create New Angular App

Run the following command on command prompt to install angular app:

ng new my-new-app

Step 2 – Install ng-file-upload Directive & toastr Notification

Run the following command on command prompt to install ng-file-upload Directive & toastr Notification in angular 12 app:

npm install @angular/animations --save

npm install ng2-file-upload

Then, add the ngx-toastr CSS in angular.json file:

"styles": [
    "src/styles.css",
    "node_modules/ngx-toastr/toastr.css"
]
"styles": [
    "src/styles.css",
    "node_modules/ngx-toastr/toastr.css"
]

Step 3 – Import Installed Modules on app.module.ts

Import HttpClientModule, FormsModule, FileSelectDirective and ToastrModule in app.module.ts file like following:

import { FileSelectDirective } from 'ng2-file-upload';
import { FormsModule } from '@angular/forms';
import { ToastrModule } from 'ngx-toastr';
@NgModule({
  declarations: [
    FileSelectDirective
  ],
  imports: [
    FormsModule
    BrowserModule,
    BrowserAnimationsModule,
    ToastrModule.forRoot()
  ]
})
export class AppModule { }

Step 4 – Create File Upload Form

Create html markup for file upload form with input file element and image tag. So, visit src/app/app.component.html and update the following code into it:

<div class="wrapper">
  <h2>Angular Image Upload</h2>
  <div class="file-upload">
    <input type="file" name="image" ng2FileSelect [uploader]="uploader" accept="image/x-png,image/gif,image/jpeg" />
    <button type="button" (click)="uploader.uploadAll()" [disabled]="!uploader.getNotUploadedItems().length">
      Upload
    </button>
  </div>
</div>

Step 5 – Import Components app.component.ts

Go to the src/app directory and open app.component.ts. Then add the following code into it:

import { Component, OnInit } from '@angular/core';
import { FileUploader } from 'ng2-file-upload/ng2-file-upload';
import { ToastrService } from 'ngx-toastr';
const URL = 'http://localhost:3000/upload';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  public uploader: FileUploader = new FileUploader({
    url: URL,
    itemAlias: 'image'
  });
  constructor(private toastr: ToastrService) { }
  ngOnInit() {
    this.uploader.onAfterAddingFile = (file) => {
      file.withCredentials = false;
    };
    this.uploader.onCompleteItem = (item: any, status: any) => {
      console.log('Uploaded File Details:', item);
      this.toastr.success('File successfully uploaded!');
    };
  }
}

Then execute the following command on terminal to start the app to check out the File upload in the browser:

ng serve --open

Create Node Express JS Backend

Use the below given steps to create node js express app for file upload to storage and db; as follows:

Step 1 – Create Node JS App

Run the following command on command prompt to create node js app:

mkdir my-app
cd my-app
npm init -y

Step 2 – Install Express body parser and cors Dependencies

Run the following commands to install imperative npm packages which will help us to create REST APIs for your angular file upload app:

npm install express express-fileupload body-parser cors
npm install nodemon --save-dev

Step 3 – Create Server.js File

In this step, add the following code into it:

const express = require("express");
const fileupload = require("express-fileupload");
const cors = require("cors");
const bodyParser = require('body-parser');
const app = express();
app.use(cors());
app.use(fileupload());
app.use(express.static("files"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post("/upload", (req, res) => {
  const newpath = __dirname + "/files/";
  const file = req.files.file;
  const filename = file.name;
  file.mv(`${newpath}${filename}`, (err) => {
    if (err) {
      res.status(500).send({ message: "File upload failed", code: 200 });
    }
    res.status(200).send({ message: "File Uploaded", code: 200 });
  });
});
app.listen(3000, () => {
  console.log("Server running successfully on 3000");
});

Step 4 – Start Node JS App

Start the server with the following command and then you can test the form:

npm start

OR

nodemon server.js

Conclusion

Angular + node express js file upload example tutorial; you have learned how to upload file in angular js app using node js express rest api.

Recommended Angular + Node Express JS Tutorials

Leave a Comment