Uploading images is a common requirement in Angular applications and this article will show you how easy it is to solve that problem in angular 8.

Angular 8 File Upload Tutorial With Example | Angular Image Upload is today’s topic. If you are new to Angular 8, then check out Angular 8 Tutorial.In this Angular Image Upload demo, we will use the ng2-file-upload library to upload a file to the node server. We use Node.js as a backend server. We install Angular using Angular 8 CLI and then start working on this Angular File Upload demo. For handling the uploaded files at the backend server, we use **the multer **library.

Content Overview

  • 1 Angular 8 File Upload Tutorial
  • 2 #Install rxjs-compat library
  • 3 #Install Bootstrap 4
  • 4 #Install an ng-file-upload library
  • 5 #Create Node.js backend

Angular 8 File Upload Tutorial

Now, set up the angular project using the following command.

ng new ng8fileupload

Now, spin up the angular app using the following command.

ng serve --open

#Install rxjs-compat library

So, to fill the gap between Angular 8 and third-party packages, we need to install the rxjs-compat library. That is it.

npm install rxjs-compat --save

Now, you will not get any error regarding any rxjs observables.

#Install Bootstrap 4

Go to your terminal and type the following command.

npm install bootstrap --save

Now, include that above file inside the **angular.json **file.

"styles": [
   "src/styles.css",
   "./node_modules/bootstrap/dist/css/bootstrap.min.css"
 ],

It will include the library in Angular application.

#Install an ng-file-upload library

Type the following command to install the library.

npm install ng2-file-upload --save

Now, write a following code inside **an app.module.ts **file.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FileSelectDirective } from 'ng2-file-upload';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
    FileSelectDirective
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

We have imported the **FileSelectDirective **from ng2-file-upload.

Also, we need to import the FormsModule. We need FormsModule because we need to write the file upload component.

Now, write the following code inside an **app.component.ts **file.

// app.component.ts

import { Component, OnInit } from '@angular/core';
import {  FileUploader, FileSelectDirective } from 'ng2-file-upload/ng2-file-upload';

const URL = 'http://localhost:4000/api/upload';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'ng8fileupload';
  public uploader: FileUploader = new FileUploader({ url: URL, itemAlias: 'photo' });
  ngOnInit() {
    this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; };
    this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
         console.log('ImageUpload:uploaded:', item, status, response);
         alert('File uploaded successfully');
    };
 }
}

n the above code, we have imported **FileUploader **and **FileSelectDirective **from ng2-file-upload.

Also, we have defined the backend API URL, which is http://localhost:4000/api/upload.

We will create a backend server in Node.js and then send a POST request to the server.

So, here we have used the Angular Component lifecycle. The function is ngOnInit().

We have written the file upload code inside the ngOnInit function.

Now, the only thing remaining is written the HTML code for the file upload component.

Write the following piece code inside the **app.component.html **file.


  
  <button type="button" class="btn btn-success btn-s" 
    (click)="uploader.uploadAll()" 
    [disabled]="!uploader.getNotUploadedItems().length" >
        Upload an Image
  


Now, go to the http://localhost:4200/** **URL and see the output.

Now the only thing remaining is to create a backend in Node.js.

#Create Node.js backend

First, install the following node modules.

npm install express multer body-parser dotenv --save

Install nodemon as a dev dependency.

npm install nodemon --save-dev

Create a new directory inside root of angular project called uploads.

Okay, now create one file in the angular project root folder called server.js.

Write the following piece code inside the **server.js **file.

// server.js

const path = require('path');
const express = require('express');
const multer = require('multer');
const bodyParser = require('body-parser')
const app = express();

const DIR = './uploads';
 
let storage = multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, DIR);
    },
    filename: (req, file, cb) => {
      cb(null, file.fieldname + '-' + Date.now() + '.' + path.extname(file.originalname));
    }
});
let upload = multer({storage: storage});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
 
app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
  res.setHeader('Access-Control-Allow-Methods', 'POST');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
  res.setHeader('Access-Control-Allow-Credentials', true);
  next();
});
 
app.get('/api', function (req, res) {
  res.end('file catcher example');
});
 
app.post('/api/upload',upload.single('photo'), function (req, res) {
    if (!req.file) {
        console.log("No file received");
        return res.send({
          success: false
        });
    
      } else {
        console.log('file received');
        return res.send({
          success: true
        })
      }
});
 
const PORT = process.env.PORT || 4000;
 
app.listen(PORT, function () {
  console.log('Node.js server is running on port ' + PORT);
});

First, we have used process.env. Working with environment variables is a great way to configure different configurations of your Node.js application.

If the environment variable PORT is defined inside the .env file, then it will take that variable’s value; otherwise, it will pick the value of by default, and in our case, it is 4000. So node.js will spin up on the port 4000.

We have imported the **multer **library. It is the node.js compatible library to handling file or image handling in the node.js.

We can store the file using the multer’s file storage function.

When the HTTP POST request of the file is coming to the node.js server, then first we have used the body-parser module which parses the request data and then go to the multer function and extract the file from the request and add the timestamp to the filename and save the file inside the **uploads **directory. We have already defined the directory.

The final step is to start the node.js server using the following code.

nodemon server

Now, go to the frontend and try to upload a file. I have tried to upload an image, and it is successfully uploaded. You can see the alert() on the frontend.

This is the primary example of Image Upload in Angular 8. If you want to resize the image using the node.js, then check out my Node.js image resize tutorial.

Also, see the **uploads **folder to see if the image is saved or not.

You can find more options on ng2-file-upload official documentation.

Finally, **Angular 8 File Upload Tutorial With Example | Angular Image Upload **is over. Thanks for taking.

#angular #web-development

Angular 8 File Upload Tutorial With Example | Angular Image Upload
5 Likes559.50 GEEK