Latest Code Tutorials

Angular 6 File Upload Tutorial


Angular 6 File Upload Tutorial. In this example, We will use an ng2-file-upload library to upload a file to the server. We use Node.js as a backend server. We install Angular 6 using Angular CLI and then start working on this Angular File Upload demo. For managing the uploaded files at the backend, we use the multer library.

If you want to learn more about Angular 7 then check out this Angular 7 – The complete Guide course.

Angular 6 File Upload Tutorial

We start this project by installing Angular on our machine.

Step 1: Install Angular 6.

If you have not installed Angular CLI globally on your machine, then install it using the following command.

npm install -g @angular/cli

# or

yarn add global @angular/cli

Now, create a local project using the following command.

ng new fileupload

Now, start the application using the following command.

ng serve --open

Step 2: Install rxjs-compat library.

Since third-party libraries do not support the RxJS 6. Now, one change in Angular 6 is that Angular 6 now depends on TypeScript 2.7 and RxJS 6. So, if you install third-party packages right now, then it is not compatible with Angular 6. In future, all the third-party libraries might upgrade their packages, but right now, it is not compatible with Angular 6.

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

npm install rxjs-compat --save

Step 4: Install Bootstrap 4.

Go to your terminal and type the following command.

npm install bootstrap --save

After that go to the inside src folder and open styles.css file and import the bootstrap.min.css file.

@import "~bootstrap/dist/css/bootstrap.min.css"

Step 5: Install ng-file-upload library.

Type the following command to install the library.

npm install ng2-file-upload --save

Now, write the 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';

  declarations: [
  imports: [
  providers: [],
  bootstrap: [AppComponent]
export class AppModule { }

Okay, so we have imported FormsModule and FileSelectDirective.

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:3000/api/upload';

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent implements OnInit {
  title = 'app';

  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');

Finally, write the following code inside an app.component.html file.

<input type="file" name="photo" ng2FileSelect [uploader]="uploader" />

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


Angular 6 File Upload Tutorial

Step 6: Create Node.js backend.

First, install the following node modules.

npm install express multer body-parser --save

Install nodemon as a dev dependency.

npm install nodemon --save-dev

Create a new directory inside root called uploads.

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

// server.js

const path = require('path');
const fs = require('fs');
const express = require('express');
const multer = require('multer');
const bodyParser = require('body-parser')
const app = express();
const router = express.Router();

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

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);
app.get('/api', function (req, res) {
  res.end('file catcher example');
});'/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 || 3000;
app.listen(PORT, function () {
  console.log('Node.js server is running on port ' + PORT);

So, I have used multer module to store the file.

Now, start the server using the following command.

nodemon server

Step 7: Run the project.

Start both the server, if not started.

  1. ng server –open
  2. nodemon server

Go to the http://localhost:4200/

Now, until you have not selected any file, the upload an image button will remain disabled.

Upload an image, and see the response you get in the browser console.

Angular Node.js Image Upload


Finally, Angular 6 File Upload Tutorial is over. Thanks for taking.

  1. Brian S says

    Great tutorial. Working perfect.

  2. Troy says

    How to display the images after they are stored

  3. Robin Singh says

    I watched many tutorials but u r the best.
    i m trying from last 2 weeks but nothing happens. Thanku for this tutorial.

    Can u make a new tutorial on how to show image after save in folder and database

  4. Ganesh says

    Is this work in a2hosting or Godaddy server? In the local server it is working fine.

  5. Gopi says

    This is what I am exactly looking for. Got it. Great thanks Krunal.

  6. Nize says

    Thank you so much.

  7. mohan says

    not working for me .anyone please help me
    send me tour code to

    1. prasanna says

      carefully follow every command, even it didn’t worked for me in the beginning

  8. jaballi aymen says

    thkns for that 🙂
    but how get link this image uplouder!!

    1. bhawna inaniya says

      please perform this operation with form data

  9. bhawna inaniya says

    please send detail about how to add post data with ng2 uploader

  10. Almeida says

    How can I show the image that was uploaded? To upload an image is easy, but I don`t get how can I fetch it and show it 🙁

  11. Pankaj Makwana says

    Can you please let me know how to send header with file uploading? I want to send authentication token, and other headers

  12. best iptv says

    great share.
    I think the most stable premium iptv servers are those from Fishbone IPTV cloud
    I would like to see more posts like this

  13. Mohamed Motyim says

    Thanks a lot this help me

  14. Aditya says

    Getting 404 error while using same with spring rest api on angular 6

  15. Rozy Mahsun says

    How to upload multiple files ?
    Thanks in advanec

  16. Mladen says

    UploadCatalogComponent.html:8 ERROR TypeError: Cannot read property ‘uploadAll’ of undefined

  17. Katheeja says

    has no exported member ‘FileSelectDirective’.Why I get this error?

  18. Katheeja says

    Thanks a lot, How to do file download from server using angular and node.js.Please share snippet.

  19. Katheeja says

    Thanks a lot,upload worked but I am unable to download in original file name. Please help.

  20. Nhi says

    Hi, I have an error: OPTIONS http://localhost:3000/image net:: ERR_CONNECTION_REFUSED
    Please help me. Thanks

  21. jeevanandan says

    I need to send form values also, how can i send?

  22. jk says

    where is the file stored after uploading

  23. jk says

    where is the file stored after uploading

    1. Esteban Potes Rua says

      in the uploads folder

      1. cvvb says

        where is the upload folder

  24. Esteban Potes Rua says

    How to use the download of those files?

  25. Shah Maz says

    I got another issue. after running server.js upload works perfect but I got 404 Err ‘File NOT found’ from another method I already have.

    this.httpClnt.get (‘assets/daily.json’); //it works before running server.js but after running httpClient Get json files not working

    any idea

  26. Nethravathi says

    Can any please help me with the code to upload csv and xlsx file in angular 6?

  27. imran says

    how to upload csv file into mongodb in mean stack angular 7

  28. mounika says

    It’s not working for me can you please any share code.

  29. sathya says

    It’s working fine up to UI but it’s not working in services part for me
    Ex: in my project i am getting service path http://localhost:3000/api/upload always not found 404 error
    Can you please any one help me for this.

  30. rgreerre says

    updating image how can it be done

    1. yutu says

      ye i want to know

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.