AppDividend
Latest Code Tutorials

Angular 6 File Upload Tutorial

33,124

Get real time updates directly on you device, subscribe now.

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

@NgModule({
  declarations: [
    AppComponent,
    FileSelectDirective
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  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';

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

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

 

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.

Related Posts
1 of 17
// 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);
});

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.

20 Comments
  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 amohanagarapu@gmail.com

    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

    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

  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.

Leave A Reply

Your email address will not be published.

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