Angular File Upload [Step-by-Step Guide]

To upload files in Angular, use the ng2-file-upload library. For managing the uploaded files at the backend, we use the multer library. Multer is a node.js middleware for handling multipart/form-data, primarily for uploading files. 

Here is the step-by-step guide to upload a file in Angular.

Step 1: Install Angular.

npm install -g @angular/cli

# or

yarn add global @angular/cli

Create a local project using the following command.

ng new fileupload

Start the application using the following command.

ng serve --open

Step 2: Install the rxjs-compat library.

npm install rxjs-compat --save

Step 3: Install Bootstrap 4.

Go to your terminal and type the following command.

npm install bootstrap --save

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

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

Step 4: Install the ng-file-upload library.

Type the following command to install the library.

npm install ng2-file-upload --save

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

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

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

@Component({
  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');
     };
 }
}

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" 
  (click)="uploader.uploadAll()" 
  [disabled]="!uploader.getNotUploadedItems().length" >
      Upload an Image
</button>

Angular 6 File Upload Tutorial

Step 5: Create Node.js backend.

Install the following node modules.

npm install express multer body-parser --save

We have installed Express as a web framework for Node.js development.

Install nodemon as a dev dependency.

npm install nodemon --save-dev

Create a new directory inside the root called uploads.

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 + '-' + 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 || 3000;
 
app.listen(PORT, function () {
  console.log('Node.js server is running on port ' + PORT);
});

Boot up the server using the following command.

nodemon server

Step 6: Run the project.

Start both servers if not started.

  1. ng server –open
  2. nodemon server

Go to the http://localhost:4200/

Once you select any file, the upload an image button will remain disabled.

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

Angular Node.js Image Upload

When encountering an error, Multer will delegate the error to Express. Thus, you can display a nice error page using the standard expressway.

To catch errors specifically from Multer, you can call the middleware function yourself. Also, if you’re going to catch only the Multer errors, you can use the MulterError class that is attached to the multer object itself (e.g. err instanceof multer.MulterError).

// server.js
var multer = require('multer')
var upload = multer().single('avatar')
 
app.post('/profile', function (req, res) {
  upload(req, res, function (err) {
    if (err instanceof multer.MulterError) {
      // A Multer error occurred when uploading.
    } else if (err) {
      // An unknown error occurred when uploading.
    }
 
    // Everything went fine.
  })
})

That’s it for this tutorial. Thanks for taking it.

39 thoughts on “Angular File Upload [Step-by-Step Guide]”

  1. 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

    Reply
  2. bonjour
    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
    Thanks

    Reply
  3. 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

    Reply
  4. ng build –prod getting error:
    Please consider moving FileSelectDirective in node_modules/ng2-file-upload/file-upload/file-select.directive.d.ts to a higher module that imports AppModule in src/app/app.module.ts and FileUploadModule in node_modules/ng2-file-upload/file-upload/file-upload.module.d.ts. You can also create a new NgModule that exports and includes FileSelectDirective in node_modules/ng2-file-upload/file-upload/file-select.directive.d.ts then import that NgModule in AppModule in src/app/app.module.ts and FileUploadModule in node_modules/ng2-file-upload/file-upload/file-upload.module.d.ts.

    Reply

Leave a Comment

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