Ng2-file-upload Error Cannot Read Property isuploading of Undefined

File Upload is one of those things that is not as straight forward only gets easier once we get our heads effectually it. In this tutorial, nosotros volition meet how we can implement File Upload using Angular 2 and Node.js. Nosotros have already covered Athwart 1 variation of this topic in 1 of our previous tutorial.

This tutorial comprises of two parts.

  • Dorsum-end with NodeJS/ ExpressJS and Multer
  • Browser Application with Angular 2 and ng2-File-Upload

Without further ado, let'south get started.

Back-end with NodeJS/ ExpressJS and Multer

The back-end implementation for File Upload with Node.js is more or less like to the ane nosotros did in our post for file upload with Angular one and Node. In that location is merely one change and that is we will be enabling CORS on our Node server. So here I'll just display the lawmaking, for a detailed explanation please visit this link.

DEMODOWNLOAD

Let'south get-go past creating a project directory.


At present, let's navigate into the working directory and create a directory for our Node.js application.

cd file-upload-demo
mkdir node-app

cd node-app

package.json

          

{
"name" : "expapp" ,
"version" : "ane.0.0" ,
"description" : "" ,
"principal" : "app.js" ,
"scripts" : {
"test" : "echo "Error: no test specified" && exit 1"
} ,
"writer" : "" ,
"license" : "ISC" ,
"devDependencies" : {
"gulp" : "3.ix.0" ,
"gulp-develop-server" : "0.v.0" ,
"gulp-jshint" : "ane.12.0"
} ,
"dependencies" : {
"trunk-parser" : "one.xiv.1" ,
"express" : "four.13.iii" ,
"fs" : "0.0.2" ,
"multer" : "1.ane.0"
}
}

app.js

          

var express = require( 'express' ) ;
var app = express( ) ;
var bodyParser = require( 'body-parser' ) ;
var multer = require( 'multer' ) ;

    app.use ( function (req, res, next) { //allow cross origin requests
res.setHeader ( "Admission-Control-Permit-Methods" , "POST, PUT, OPTIONS, DELETE, Go" ) ;
res.header ( "Access-Control-Allow-Origin" , "http://localhost:3000" ) ;
res.header ( "Access-Control-Allow-Headers" , "Origin, Ten-Requested-With, Content-Type, Take" ) ;
res.header ( "Access-Control-Allow-Credentials" , truthful ) ;
adjacent( ) ;
} ) ;

/** Serving from the same express Server
No cors required */

app.use (express.static ( '../client' ) ) ;
app.use (bodyParser.json ( ) ) ;

var storage = multer.diskStorage ( { //multers disk storage settings
destination: office (req, file, cb) {
cb( zero , './uploads/' ) ;
} ,
filename: function (req, file, cb) {
var datetimestamp = Date.now ( ) ;
cb( null , file.fieldname + '-' + datetimestamp + '.' + file.originalname.divide ( '.' ) [file.originalname.divide ( '.' ).length - 1 ] ) ;
}
} ) ;

var upload = multer( { //multer settings
storage: storage
} ).unmarried ( 'file' ) ;

/** API path that will upload the files */
app.postal service ( '/upload' , office (req, res) {
upload(req,res, office (err) {
panel.log (req.file ) ;
if (err) {
res.json ( {error_code: 1 ,err_desc:err} ) ;
render ;
}
res.json ( {error_code: 0 ,err_desc: null } ) ;
} ) ;
} ) ;

    app.heed ( '3001' , function ( ) {
console.log ( 'running on 3001...' ) ;
} ) ;


Nosotros are using gulp as a job runner for our Node.js app.

gulpfile.js

          

var gulp = require( 'gulp' ) ,
server = require( 'gulp-develop-server' )
jshint = require( 'gulp-jshint' ) ;

gulp.task ( 'lint' , function ( ) {
return gulp.src ( 'app.js' )
.pipe (jshint( ) )
.pipe (jshint.reporter ( 'default' ) ) ;
} ) ;

// run server
gulp.task ( 'server:offset' , function ( ) {
server.listen ( { path: './app.js' } ) ;
} ) ;

// restart server if app.js inverse
gulp.job ( 'server:restart' , function ( ) {
gulp.watch ( [ './app.js' ] , server.restart ) ;
} ) ;

gulp.chore ( 'default' , [ 'lint' , 'server:start' , 'server:restart' ] ) ;

We need to have a directory where our uploaded files will go.


Install all dependencies, and as well install gulp globally.

npm install

npm install gulp -yard


Nosotros can start upwardly the server with the below command.

If everything was setup properly y'all should be able to see the post-obit output on the console.

File Upload with NodeJS
Node.js server

Browser Application with Angular 2 and ng2-File-Upload

Since you lot are hither, and looking to implement file-upload in Angular 2, I recollect information technology'due south prophylactic to assume that yous accept a basic Athwart 2 application ready and that your auto is setup to run Angular 2 application. Then I'll skip the setup part and start with a basic pre-built Angular two awarding. If you however wish to know the nuts in Angular 2 you can visit the below articles.

  • Build a single folio awarding wth Athwart 2
  • Athwart 2 architecture

We will start by cloning the repository into our working directory (in our case information technology's /file-upload-demo).

git clone https://github.com/rahil471/angular2-fast-start.git angular2-app

cd angular2-app

Install all the dependencies.


We will be using ng2-file-upload library to help usa with the File Upload for our Angular 2 application. Let'southward install it using npm.

npm install ng2-file-upload --salvage

Now nosotros need to configure our module loader to recognize and discover ng2-file-upload. The configuration would exist specific to the module loader you lot are using. For this tutorial, nosotros are using Systems.js every bit our module loader, so we volition see the configuration for the aforementioned.

systemjs.config.js

          

/**
* System configuration for Angular samples
* Accommodate equally necessary for your application needs.
*/

( part (global) {
System.config ( {
paths: {
// paths serve as allonym
'npm:' : 'node_modules/'
} ,
// map tells the System loader where to wait for things
map: {
// our app is within the app folder
app: 'app' ,
// athwart bundles
'@angular/core' : 'npm:@angular/core/bundles/core.umd.js' ,
'@angular/mutual' : 'npm:@athwart/mutual/bundles/common.umd.js' ,
'@angular/compiler' : 'npm:@angular/compiler/bundles/compiler.umd.js' ,
'@angular/platform-browser' : 'npm:@angular/platform-browser/bundles/platform-browser.umd.js' ,
'@angular/platform-browser-dynamic' : 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js' ,
'@angular/http' : 'npm:@angular/http/bundles/http.umd.js' ,
'@athwart/router' : 'npm:@angular/router/bundles/router.umd.js' ,
'@angular/forms' : 'npm:@angular/forms/bundles/forms.umd.js' ,
// other libraries
'rxjs' :'npm:rxjs' ,
'athwart-in-memory-web-api' : 'npm:athwart-in-memory-web-api' ,
/** Path for ng2-file-upload */
'ng2-file-upload' : 'npm:ng2-file-upload'
/** Path for ng2-file-upload */
} ,
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: './transpiled-js/main.js' ,
defaultExtension: 'js'
} ,
rxjs: {
defaultExtension: 'js'
} ,
'angular-in-retention-spider web-api' : {
main: './index.js' ,
defaultExtension: 'js'
} ,
/** Configuration for ng2-file-upload */
'ng2-file-upload' : {
principal: './ng2-file-upload.js' ,
defaultExtension: 'js'
}
/** Configuration for ng2-file-upload */
}
} ) ;
} ) ( this ) ;


The ng2-file-upload module provides us with a few directives for achieving file upload, we need to import them and add them to declaration of our AppModule before we can use them.

app.module.ts

          

import { NgModule } from '@angular/core' ;
import { BrowserModule } from '@athwart/platform-browser' ;
import { FileSelectDirective, FileDropDirective } from 'ng2-file-upload' ;

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

@NgModule( {
imports: [BrowserModule] ,
exports: [ ] ,
declarations: [AppComponent, FileSelectDirective] , /** The FileSelectDirective is what we will require*/
providers: [ ] ,
bootstrap: [AppComponent]
} )
consign form AppModule { }

We are importing and calculation FileSelectDirective to the declarations, if we also want to implement the drag and drop characteristic we will accept to add the FileDropDirective .

Basic Usage

In our app.component.ts we will import the FileUploader form and create an uploader object of blazon FileUploader.

app/app.component.ts

          

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

@Component( {
selector: 'my-app' ,
template: `
....
.....
`
} )
consign class AppComponent {
public uploader:FileUploader = new FileUploader( {url: 'http://localhost:3001/upload' } ) ;
}

Nosotros are passing the upload URL of our Node.js application which we created earlier in the tutorial in the statement object of FileUploader.
To make this piece of work in our template we will add a ng2FileSelect directive to an html input of type file, we will as well set the [uploader] property to our uploader object.

For a single file, the input should await like beneath

<div class = "form-group">
<label for = "single">single</ label>
<input type = "file" grade = "grade-control" name = "single" ng2FileSelect [uploader] = "uploader" />
</ div>

To enable selection of multiple files we only need to add the multiple attribute of HTML5.
The uploader object stores all the selected files in a queue. To upload all the file at once nosotros can call uploader.uploadAll() part or we can call the upload() function availaible on each item of the queue.

<button type = "button" course = "btn btn-success btn-s"
(click) = "uploader.uploadAll()" [ disabled ] = "!uploader.getNotUploadedItems().length">
<span class = "glyphicon glyphicon-upload"></ span> Upload all
</ button><br />

This much in your template should exist enough to get the bones affair going, but it's non that presentable, and so nosotros will add a few more elements and attempt to brand information technology more interactive. We are using bootstrap for styling, yous are free to use a framework of your option.

The consummate template our app.component.ts would look like this.

app/app.component.ts

          

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

@Component( {
selector: 'my-app' ,
template: `<nav grade = "navbar navbar-default" >
<div class = "container-fluid" >
<div course = "navbar-header" >
<div class = "collapse navbar-plummet" id= "bs-example-navbar-collapse-i" >
<ul class = "nav navbar-nav" >
<li><a>File Upload</a></li>
</ul>
</div>
</div>
</div>
</nav>
<div class = "container" >
<div form = "row" >
<div class = "col-doc-4" >
<course>
<div grade = "grade-group" >
<characterization for = "multiple" >Multiple</label>
<input blazon= "file" class = "form-control" name= "multiple" ng2FileSelect [uploader] = "uploader" multiple/>
</div>
<div class = "form-group" >
<label for = "single" >single</characterization>
<input blazon= "file" class = "grade-command" name= "unmarried" ng2FileSelect [uploader] = "uploader" />
</div>
</form>
</div>
<div grade = "col-md-8" >
<h3>File Upload with Athwart 2 and Node</h3>
Queue length: { { uploader?.queue ?.length } }

<table class = "table" >
<thead>
<tr>
<th width= "50%" >Name</th>
<th>Size</th>
<th>Progress</th>
<th>Status</th>
<thursday>Actions</th>
</tr>
</thead>
<tbody>
<tr *ngFor= "permit item of uploader.queue" >
<td><potent> { { item.file.name } } </strong></td>
<td nowrap> { { detail.file.size / 1024 / 1024 | number: '.two' } } MB</td>
<td>
<div grade = "progress" style= "margin-bottom: 0;" >
<div grade = "progress-bar" role= "progressbar" [ngStyle] = "{ 'width': item.progress + '%' }" ></div>
</div>
</td>
<td grade = "text-eye" >
<span *ngIf= "particular.isSuccess" ><i class = "glyphicon glyphicon-ok" ></i></span>
<span *ngIf= "item.isCancel" ><i grade = "glyphicon glyphicon-ban-circle" ></i></bridge>
<bridge *ngIf= "item.isError" ><i grade = "glyphicon glyphicon-remove" ></i></span>
</td>
<td nowrap>
<push button blazon= "button" class = "btn btn-success btn-xs"
(click) = "item.upload()" [disabled] = "particular.isReady || particular.isUploading || item.isSuccess" >
<span class = "glyphicon glyphicon-upload" ></span> Upload
</button>
<button type= "push button" class = "btn btn-warning btn-xs"
(click) = "item.abolish()" [disabled] = "!item.isUploading" >
<bridge form = "glyphicon glyphicon-ban-circle" ></span> Abolish
</button>
<button type= "button" form = "btn btn-danger btn-xs"
(click) = "item.remove()" >
<bridge grade = "glyphicon glyphicon-trash" ></bridge> Remove
</button>
</td>
</tr>
</tbody>
</table>

<div>
<div>
Queue progress:
<div grade = "progress" fashion= "" >
<div class = "progress-bar" role= "progressbar" [ngStyle] = "{ 'width': uploader.progress + '%' }" ></div>
</div>
</div>
<button blazon= "push" class = "btn btn-success btn-due south"
(click) = "uploader.uploadAll()" [disabled] = "!uploader.getNotUploadedItems().length" >
<span form = "glyphicon glyphicon-upload" ></span> Upload all
</button>
<button type= "button" grade = "btn btn-warning btn-s"
(click) = "uploader.cancelAll()" [disabled] = "!uploader.isUploading" >
<span form = "glyphicon glyphicon-ban-circle" ></bridge> Cancel all
</push button>
<button blazon= "push" form = "btn btn-danger btn-s"
(click) = "uploader.clearQueue()" [disabled] = "!uploader.queue.length" >
<bridge class = "glyphicon glyphicon-trash" ></bridge> Remove all
</button>
</div>
</div>
</div>
</div>`
} )
export class AppComponent {
public uploader:FileUploader = new FileUploader( {url: 'http://localhost:3001/upload' } ) ;
}

As I said earlier each file is stored in a queue. Hence, we are repeating through the queue using the ngFor directive. Each item has the post-obit important properties.

  • file- File object which contains details related to respective file, including name, size and more.
  • progress- Progress of the particular beign uploaded in per centum.
  • upload()- Method to upload the file.
  • cancel()- Cancels and ongoing upoad.
  • remove()- Removes item from queue.

And there are a few more than properties. Have a closer await at the template to empathize them. Apart from the backdrop and methods on each item we as well accept methods that operate on the unabridged queue. For eg: uploadAll(), cancelAll(), removeAll().

Also, delight annotation when nosotros are uploading multiple files together, information technology does not send all files at once, instead the ng2-file-uploader calls the upload API multiple times depending on the number of items, uploading one at a time.

To commencement the application run the below command.

If you lot've followed forth properly you should come across the following screen on your browser running at localhost:3000.

File Upload Angular 2
Earlier Upload

Considering you have the Node.js app running, you should be able to upload files.

File Upload Angular 2
After Upload

Quick Setup

We know this has been a long tutorial and there are chances you might have slipped at one or two places. No worries, yous can quickly get the demo running by post-obit the below steps.

  • git clone https://github.com/rahil471/File-upload-Angular2-Nodejs.git file-upload
  • Navigate into the node app cd file-upload/node-app
  • Install Dependencies npm install
  • Install gulp globally npm install gulp -m
  • To start the node server gulp
  • Open up a new final window.
  • Navigate into /angular2-app/
  • Install all dependencies npm install
  • In some cases you might have to isntall lite-server globally npm i lite-server -g
  • Run the Angular two app using npm offset

DEMODOWNLOAD

Determination

File Upload is ane of the most common requirements for any spider web-application and sometimes information technology can become a hiccup, but not after this tutorial. In this tutorial, we learned how we can implement File Upload using Node.js and Angular two with ease.

More Angular 2 Stuff

  1. Angular 2 Official Documentation
  2. Acquire Angular 2 From our Free Video Course on YouTube
  3. Learn Angular 2 by building 12 apps
  4. Angular 2 by Istvan Novak

faulknerwittentiou.blogspot.com

Source: https://ciphertrick.com/file-upload-with-angular2-nodejs/

0 Response to "Ng2-file-upload Error Cannot Read Property isuploading of Undefined"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel