How To Upload a File With Angular 6/7 Tutorial

In this tutorial, we will see how to use the ng2-file-upload library to upload a file easily using angular 7.or Angular 6 example.

TL;DR: In this example, we will use the ng2-file-upload library with Angular 6 or Angular 7 to upload a file to the server through an easy to follow example. For the backend we use Node.js but you can use your preferred backend programming language.
We will start by installing Angular 7 or Angular 6 using the Angular CLI tool, after that we will build our Angular File Upload app. To handle the uploaded files with the Node.js backend, we will use the multer library.

You can also read our article on How to Upload a File or Image with Angular 8 and ng2-file-upload library.


1. Create Your Project Directory using Angular CLI

In case you haven’t installed the Angular CLI tool globally on your machine, then install it using the following command:


npm install -g @angular/cli
# or
yarn add global @angular/cli

After that you will be able to create a local project with this command:


ng new ngFileUpload

Where:

  • ng new: command to ask the CLI to generate a new angular application.
  • ngFileUpload: your preferred application name, you can call it anything.

Then access to your created directory using the following command:


cd ngFileUpload

Start the server using the command below:

ng serve

2. Install rxjs-compat Library.

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

So, to fill the gap between Angular 7 and third-party packages, we need to install the following library.

npm install rxjs-compat --save

3. Install Bootstrap 4

In terminal type the following command.

npm install bootstrap --save

After that go inside the src folder and open the styles.css file then import the bootstrap.min.css file using the line below.

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

Install ng2-file-upload Library

Install the ng2-file-upload library using the npm command:

npm install ng2-file-upload --save

The App module file is basically where all imports and generated files are recorded with their configuration metadata in the NgModule object. As a footnote, all components go into declarations, services into providers and modules into imports.

Now, open the app.module.ts file and past the following code.

// 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 { }

Now that we have imported the FileSelectDirective in the declarations array and the FormsModule in the imports array as shown above.

Open the app.component.ts file and write the following code inside.

// app.component.ts

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

const UploadURL = 'http://localhost:3000/api/upload';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'Upload a File';

  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('FileUpload: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>

5. Create the Node.js Backend

First, start by installing the following node modules.

npm install express multer body-parser --save

Install nodemon as a dev dependency to see new code updates by restarting the server automatically.

npm install nodemon --save-dev 

Create a new folder inside the root directory called uploads.

Now go and create a server.js file in the project root folder, and then add the following code to it.

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

As you can see I have used multer module to store the uploaded file.

After that start the backend server using the command bellow:

nodemon server

6. Test it!

Make sure that both the backend and frontend servers are running then go and visit http://localhost:4200/

Now, select any file to enable the upload button, otherwise the upload button will remain disabled. Upload an image, and see the response you get in the browser console.

Angular 7 Node.js Image Upload with ng2-file-upload

Conclusion

In this article, we got introduced to how we can upload a file easily using the ng2-file-upload library with Angular 6 or Angular 7 example.

If you are interested about Angular and Bootstrap Here is a link to the angular official documentation, and a link to bootstrap 4 documentation.

If you have any questions, you can leave them in the comments section, I will be more than happy to answer.

If this article helped you in any way, then feel free to buy me a coffee ☕ 😎

#blogger #blog #angular7 #angular6 #Angular7Tutorial

Name

Angular,7,Angular 8,1,Best Practices,1,Design,1,Firebase,1,Ionic,1,Java,5,Nodejs,2,Python,1,Restful API,1,Software Development,1,Spring,3,Spring Batch,1,Spring Boot 2,1,Web Development,1,
ltr
item
Programming Tutorials, News and Reviews: How To Upload a File With Angular 6/7 Tutorial
How To Upload a File With Angular 6/7 Tutorial
In this tutorial, we will see how to use the ng2-file-upload library to upload a file easily using angular 7.or Angular 6 example.
https://2.bp.blogspot.com/-aOru2g8VvnE/XEY8XIz5gNI/AAAAAAAAANU/QSi0Wr6jubox_3Ke3r86EOa_qjbGO7PdwCLcBGAs/s1600/Angular-7-6-Node.js-Image-Upload.png
https://2.bp.blogspot.com/-aOru2g8VvnE/XEY8XIz5gNI/AAAAAAAAANU/QSi0Wr6jubox_3Ke3r86EOa_qjbGO7PdwCLcBGAs/s72-c/Angular-7-6-Node.js-Image-Upload.png
Programming Tutorials, News and Reviews
https://www.ninjadevcorner.com/2019/01/how-to-upload-file-with-angular-6-7-tutorial.html
https://www.ninjadevcorner.com/
https://www.ninjadevcorner.com/
https://www.ninjadevcorner.com/2019/01/how-to-upload-file-with-angular-6-7-tutorial.html
true
493653397416713395
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS CONTENT IS PREMIUM Please share to unlock Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy