Saturday, November 16, 2024
Google search engine
HomeLanguagesAngularAngular 12 + Node JS File Upload Tutorial with Example

Angular 12 + Node JS File Upload Tutorial with Example

Angular 12 + Node Express file/image upload with form data example. In this tutorial, you will learn how to upload file/image in angular app with node express js.

For the backend, this tutorial will use a simple node express js application that exposes a unique endpoint that accepts a POST request containing the file/image to upload.

Before starting this angular js + node express js file upload tutorial; you’ll need to have Node.js installed which can be done by following the instructions on this tutorial.

Angular 12 + Node Express JS File Upload Tutorial with Example

  • 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

Step 1 – Create New Angular App

First of all, open your terminal and execute the following command on it to install angular app:

ng new my-new-app

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

Open your terminal and execute the following command 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"
]

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

Then, Open app.module.ts file and import HttpClientModule, FormsModule, FileSelectDirective and ToastrModule to 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

In this step, 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

In this step, visit 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

Step 1 – Create Node JS App

Open your terminal and execute the following command to create node js app:

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

Step 2 – Install Express body parser and cors Dependencies

Execute 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

RELATED ARTICLES

Most Popular

Recent Comments