Skip to content

All topics  /  Angular

How to Upload File in Angular 14 with Node JS?

Angular ·

For teams turning “How to Upload File in Angular 14 with Node JS?” into a repeatable delivery task, training efficiency can document setup, troubleshooting and review time; managers should interpret those records alongside reliability and completed work, not as a stand-alone score.

Package and operating-system behaviour can change, so verify the commands and supported versions through the Node.js project before running them on a production host.

Hello Friends,

If you need to see an example of how to upload a file/image in the angular app with node express js. we will help you to give an example of an angular 14 node js file upload. if you have a question about how to upload files in angular with node js then I will give a simple example with a solution. let’s discuss upload files in angular. Let's see the bellow example image and file upload using node js in angular.

In this tutorial, we will learn how to upload a file or image in an Angular 14 app using Node Express.js. We'll demonstrate how to use form data to accomplish this task.

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