How to Upload a File Image with Angular 8: Step by Step Tutorial

Another Angular 8 Tutorial explaining how to upload a file or an image easily with angular 8 and the ng2-file-upload third-party library. In this tutorial we are going to walk through the process of uploading a file or image to a Node.js server using the ng2-file-upload library.

angular file upload with ng2-file-upload library exampleHi folks for another Angular 8 Tutorial explaining how to upload a file or an image easily with angular 8 and the ng2-file-upload third-party library. If you are new to Angular 8 you can check out my article Angular 8 Features with Ivy Explained to learn more about it. In this tutorial we are going to walk through the process of uploading a file or image to a Node.js server using the ng2-file-upload library. First of all, we need to create an angular project using the Angular 8 CLI, and then we will implement this Angular file upload example. The Node.js backend uses the multer library to handle the uploaded files.

Create an Angular 8 File Upload App

Generate your Angular 8 project using the command below:

ng new ng8fileupexample

create an angular 8 file upload app

To test that the app is working, we can run our application using the following command:

ng serve

Then, navigate to http://localhost:4200 and you will see an Angular page showing that everything is working great.

Handle Compatibility Issues with rxjs-compat Library

The ng2-file-upload library that depends on the RxJS 5 package will not work with the new Angular 8 which makes use of RxJS 6. To solve this problem, we need to install the rxjs compatibility layer package, rxjs-compat. To install it type in the following command.

npm install rxjs-compat --save

After that, no errors will be triggered concerning the rxjs observables.

Install Bootstrap 4

We decided to work with Bootstrap as a css library for our project; you can choose any library you want. This is the command you need to install Bootstrap 4.

npm install bootstrap --save

Next, add the following script to your angular.json file

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

Install the ng2-file-upload library

Use the command below to install the ng2-file-upload library.

npm install ng2-file-upload --save

Upload Files Using the ng2-file-upload library

Open your app.module.ts file, import the FileUploadModule from the ng2-file-upload and add it to the imports array like the code below.

// app.module.ts

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

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

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

We also need to import the FormsModule so our file upload component will work properly.

After that, let's include the following code into our app.component.ts file.

// app.component.ts

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

const uploadAPI = 'http://localhost:4000/api/upload'; // better use a service class

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

It is always recommended to create a service class with methods to communicate with the server for processing tasks, and then inject this service into our component which will keep it clear and clean. For simplicity reasons, in this tutorial we will omit the use of services.

We have imported the FileUploader class from ng2-file-upload to be used in our app component class.

We have defined our backend API URL with the uploadAPI variable.

We will create the Node.js app which will be responsible of handling our uploaded file.

The file upload script is created inside the Angular 8 ngOnInit function.

The last part is to write the HTML code for our component.

Open your app.component.html file and add the following code.

<div class="container">
  <input type="file" name="file" ng2FileSelect [uploader]="uploader" />
  <button type="button" class="btn btn-success btn-s" 
    (click)="uploader.uploadAll()" 
    [disabled]="!uploader.getNotUploadedItems().length" >
        Upload
  </button>
</div>

Test your app by visiting the http://localhost:4200/ URL and observe the result.

Now, let's go and create our Node.js backend server as a final step.

Handle the Uploaded Files with a Node.js Backend

First of all, let's start by installing the following node modules.

npm install express multer body-parser dotenv --save

Install the nodemon tool as a dev dependency which will be responsible of tracking any changes to our app in realtime and keep restarting the server automatically.

npm install nodemon --save-dev

Let’s create a new directory called server inside the root of our Angular 8 project.

Then, create a sub-directory called uploads into the server directory.

After that, create a file within the server directory called server.js.

Open the newly created server.js file and insert the following code inside it.

// 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 upload');
});
 
app.post('/api/upload',upload.single('file'), function (req, res) {
    if (!req.file) {
        console.log("Your request doesn’t have any file");
        return res.send({
          success: false
        });
    
      } else {
        console.log('Your file has been received successfully');
        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);
});

As you can see, this is the file which handles the file uploading process. We have imported the Node.js multer library which is responsible of extracting, naming and storing the uploaded file from the Angular 8 client app.

The POST request data is initially parsed using the body-parser module before being processed by the multer library.

The multer library stores the uploaded file image inside the folder named uploads already defined using the DIR variable.

You should also keep in mind that it is a good practice to work with environment variables like we did with the PORT variable which is defined using the process.env, so we can get different configurations for our Node.js application.

The Node.js app will kick off using the environment variable PORT defined in the .env file if it exists; otherwise, the default PORT value 4000 will be picked.

The last thing remaining to do is starting your Node.js server by opening a new terminal in the server directory and your Angular 8 app if not already served using the below commands.

nodemon server
ng serve --open

You will see an input like this one, try to upload an image file and see what's happening next.

angular file upload using ng2-file-upload library

If everything is working as expected, you will get an alert and a console message showing that the file is uploaded successfully.

how to upload a file image in angular 8

You will get a message in the Node.js console showing that the file was uploaded like the following image.

angular 8 file upload example

Also, you can access the folder uploads and see if the image file is stored on the disk or not.

angular file uploading with ng2-file-upload

To learn more about the on ng2-file-upload configurations, you can check their official documentation and see more features regarding the file upload system like the Drag and Drop file upload using ng2-file-upload.

Takeaway

In this tutorial we have seen how to create an Angular file upload system with the ng2-file-upload library and a Node.js as a backend server.

Finally, I want to thank you for reading this tutorial and I hope that you have learned something new today with me.

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

#angular8 #angular #Angular8Tutorial #ng2-file-upload

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 Image with Angular 8: Step by Step Tutorial
How to Upload a File Image with Angular 8: Step by Step Tutorial
Another Angular 8 Tutorial explaining how to upload a file or an image easily with angular 8 and the ng2-file-upload third-party library. In this tutorial we are going to walk through the process of uploading a file or image to a Node.js server using the ng2-file-upload library.
https://1.bp.blogspot.com/-Kei2ZmGCqrc/XU3sqzns_EI/AAAAAAAAAVk/cAyNc-f3SBUP_Dw6dsj40uP7BkgDUpHcwCLcBGAs/s200/files-classified.jpg
https://1.bp.blogspot.com/-Kei2ZmGCqrc/XU3sqzns_EI/AAAAAAAAAVk/cAyNc-f3SBUP_Dw6dsj40uP7BkgDUpHcwCLcBGAs/s72-c/files-classified.jpg
Programming Tutorials, News and Reviews
https://www.ninjadevcorner.com/2019/08/how-to-upload-file-image-with-angular-8-step-by-step-tutorial.html
https://www.ninjadevcorner.com/
https://www.ninjadevcorner.com/
https://www.ninjadevcorner.com/2019/08/how-to-upload-file-image-with-angular-8-step-by-step-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