Giter Site home page Giter Site logo

ngx-upload's Introduction

Ngx-upload

Build Status codecov npm version GitHub license

Demo

https://ngx-upload.github.io

Table of contents

About

Ngx-upload is a module for the Angular framework. Ngx-upload supports drag and drop, upload progress and manages a file upload queue for you. Ngx-upload is bound to anyone presentation framework but you can use it with ng(x)-bootstrap or Angular Material Design without any problems.

Ngx-upload follows the same update cycle than Angular. Thereby, Ngx-upload 9.x.x is compatible with Angular 9, Ngx-upload 10.x.x is compatible with Angular 10, ...

Installation

Install through npm:

npm install @wkoza/ngx-upload

OR

yarn add @wkoza/ngx-upload

Setup

Just include NgxUploadModule in your root module with HttpClientModule and (FormsModule or ReactiveFormsModule):

import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {HttpClientModule} from '@angular/common/http';
import {FormsModule} from '@angular/forms';
import {NgxUploadModule} from '@wkoza/ngx-upload';

@NgModule({
  imports: [
    BrowserModule,
    HttpClientModule,
    FormsModule, // or ReactiveFormsModule
    NgxUploadModule.forRoot()
  ]
})
export class AppModule {}

Remenber: When you are in a sub module, you haven't to call the forRoot() method. You just have to import NgxUploadModule.

Ngx-upload also proposes to configure the drop zone aspect. Then, you can change the css class of your drop zone regarding the drop event:

  • When you drag a file
  • When you drop a file
  • In other cases

For this, you should add the configuration object DropTargetOptions like this :

import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {HttpClientModule} from '@angular/common/http';
import {FormsModule} from '@angular/forms';
import {NgxUploadModule, MineTypeEnum, DropTargetOptions} from '@wkoza/ngx-upload';

export const ngxDropTargetOptions: DropTargetOptions = {
  color: 'dropZoneColor',
  colorDrag: 'dropZoneColorDrag',
  colorDrop: 'dropZoneColorDrop',
  multiple: true,
  accept: [MineTypeEnum.Image, MineTypeEnum.Application_Pdf]
};

@NgModule({
  imports: [
    BrowserModule,
    HttpClientModule,
    FormsModule, // or ReactiveFormsModule
    NgxUploadModule.forRoot(ngxDropTargetOptions)
  ]
})
export class AppModule {}

In this example, you should also declare these css classes in your own css :

.dropZoneColor {
  border: 3px dotted rgba(0,0,0,0.08);
  background-color: rgba(0,0,0,0.12)
}

.dropZoneColorDrag {
  border: 3px dotted rgba(0,0,0,0.28);
  background-color: grey
}

.dropZoneColorDrop {
  border: 3px dotted rgba(0,0,0,0.08);
  background-color: rgba(0,0,0,0.12)
}

There are also 4 properties:

  • accept One or more unique file type specifiers describing file types to allow
  • capture What source to use for capturing image or video data
  • multiple A Boolean which, if present, indicates that the user may choose more than one file. Default true.
  • disableMultipart. Ngx-uploader uses, by default, the content-type multipart when it sends a file. This boolean allows to change the content-type of the request by the type of the file when its value is true.

Usage

Directive ngxDragAndDrop

Ngx-upload offers one directive for your drop zone called ngxDragAndDrop. It allows to add the files in the upload queue. During the drop event, it throws an event called onDrop that you can catch :

<form>

...

<div class="my-drop-zone" ngxDragAndDrop>
        Drop files here to upload
</div>


</form>

To finish, we can overwrite the DropTargetOptions for a specific case with this property binding :

<div class="my-drop-zone" [ngxDragAndDrop]="options">
        Drop files here to upload
</div>

Directive ngxInputFile

Ngx-upload offers one directive which allows the user to choose one or more files from their device storage. This structural directive can be use like this :

<form>

...

<div class="my-drop-zone" ngxDragAndDrop *ngxInputFile>
        Drop files here to upload
</div>


</form>

or like that with bootstrap:

<form>

...

<span class="btn btn-outline-success btn-s" *ngxInputFile>Upload local files</span>

</form>

and with Material

<form>

...

<button mat-raised-button [color]="'primary'" >
   <ng-template ngxInputFile> Upload local files</ng-template>
</button>
</form>

*ngxInputFile supports a configuration object of type InputFileOptions. For instance:

optionsInput: InputFileOptions = {
  multiple: true,
  accept: [MineTypeEnum.Image, MineTypeEnum.Application_Pdf]
};

There are 3 properties:

  • accept One or more unique file type specifiers describing file types to allow
  • capture What source to use for capturing image or video data
  • multiple A Boolean which, if present, indicates that the user may choose more than one file. Default true.

Upload queue

Each file is added to a queue that you can manage with uploader service. Here is an example :

  <div class="col-md-9" style="margin-bottom: 40px">
    <h3>Upload queue <span *ngIf="uploader.queue.length>0"> - {{ uploader.queue.length }} item(s)</span></h3>

    <div class="card text-right">
      <div style="margin: 15px">
        <ngb-progressbar showValue="true" type="success" [striped]="true" [animated]="true"
                         [value]="uploader.progressTotal"></ngb-progressbar>
      </div>
      <div class="card-block">
        <button type="button" class="btn btn-outline-success btn-s" (click)="uploader.uploadAll({method: 'POST', url: 'my_url'})"
                [disabled]="!activeUploadAllBtn()">
          Upload all
        </button>
        <button type="button" class="btn btn-outline-warning btn-s" (click)="uploader.cancelAll()"
                [disabled]="!activeCancelAllBtn()">
           Cancel all
        </button>
        <button type="button" class="btn btn-outline-danger btn-s" (click)="uploader.removeAllFromQueue()"
                [disabled]="!activeRemoveAllBtn()">
           Remove all
        </button>
      </div>
    </div>
    <div class="card" style="margin-top: 20px">

      <table class="table" style="font-size: 14px">
        <thead>
        <tr>
          <th></th>
          <th width="50%">Name</th>
          <th>Size</th>
          <th>Progress</th>
          <th>Actions</th>
        </tr>
        </thead>
        <tbody>
        <tr *ngFor="let itemFile of uploader.queue"
            [ngClass]="{'table-success' : itemFile.isSuccess, 'table-danger' : itemFile.isError, 'table-warning' : itemFile.isUploading  }">
          <td>
            <div [ngxThumbnail]="itemFile"></div>
          </td>
          <td>{{ itemFile.file.name }}</td>
          <td>{{ itemFile.file.size/1024/1024 | number:'1.0-2' }} MB</td>
          <td>
            <div>
              <ngb-progressbar type="success" showValue="true"
                               [striped]="true" [animated]="true"
                               [value]="itemFile.progress">

              </ngb-progressbar>
            </div>
          </td>
          <td style="text-align: center">
            <button type="button" class="btn btn-outline-success btn-sm" (click)="itemFile.upload({method: 'POST', url: 'my_url'})"
                    [disabled]="!itemFile.isReady">
               Upload
            </button>
            <button type="button" class="btn btn-outline-warning btn-sm" (click)="itemFile.cancel()"
                    [disabled]="!itemFile.uploadInProgress || itemFile.isCancel">
             Cancel
            </button>
            <button type="button" class="btn btn-outline-danger btn-sm" (click)="itemFile.remove()"
                    [disabled]="itemFile.isSuccess || itemFile.uploadInProgress">
              Remove
            </button>
          </td>
        </tr>
        </tbody>
      </table>
    </div>

  </div>

upload or uploadAll method require a parameter with the type UploadEndPoint. It's your server's endpoint.

Take a look at those examples for more details :

Hooks

Ngx-upload offers 7 Observable to handle a specific behavior :

  • onCancel$ : This Observable emits when upload is canceled.
  • onError$<{ item: FileItem, body: any, status: number, headers: any }> : This Observable emits on error during the upload process.
  • onSuccess$<{ item: FileItem, body: any, status: number, headers: any }> : This Observable emits on success.
  • onBeforeUploadItem$ : This Observable emits just before the upload process.
  • onProgress$<{ item: FileItem, progress: number }> : This Observable emits during the upload process.
  • onAddToQueue$<>: This Observable is trigged when a file is added in the queue.
  • onDropError$<{ item?: File, errorAccept: boolean, errorMultiple: boolean }>: This Observable is trigged when a file is not accepted in the queue.

For example :

import { Component, OnInit } from '@angular/core';
import { FileItem, HttpClientUploadService } from '@wkoza/ngx-upload';


@Component({
    selector: 'app-root',
    templateUrl: './simple.component.html',
    styleUrls: ['./simple.component.css']
})
export class SimpleBootstrapComponent implements OnInit {

    constructor(public uploader: HttpClientUploadService) { }

    ngOnInit() {

        this.uploader.onCancel$.subscribe(
            (data: FileItem) => {
                console.log('file deleted: ' + data.file);

            });

        this.uploader.onProgress$.subscribe(
            (data: any) => {
                console.log('upload file in progree: ' + data.progress);

            });

        this.uploader.onSuccess$.subscribe(
            (data: any) => {
                console.log(`upload file successful:  ${data.item} ${data.body} ${data.status} ${data.headers}`);

            }
        );


    }
}

Documentation

All documentation is auto-generated from the source via compodoc and can be viewed here: https://ngx-upload.github.io/docs/

License

MIT

ngx-upload's People

Contributors

ausshadu avatar dependabot[bot] avatar ilueckel avatar rc6886 avatar renovate[bot] avatar wkoza avatar zagronitay avatar zainniazi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

ngx-upload's Issues

Mine types

Hi,

I have this in options
public optionsInput: InputFileOptions = {
multiple: true,
accept: [MineTypeEnum.Image, MineTypeEnum.Application_Pdf],
};
but the upload file accept all types of files. I just want images and PDFs

Thanks

Not working while drag and drop of .avi file and same is working while upload by file explorer

Hi,
I have a implemented the drag and drop functionality for all types of files.
When I am drag and upload the .avi file is it getting $error and for same file if I upload by file explorer and upload it then it works.

I have added all the MIME types
// Videos
MineTypeEnum.Video,
MineTypeEnum.Video_Threegpp,
MineTypeEnum.Video_H264,
MineTypeEnum.Video_Mp4,
MineTypeEnum.Video_Mpeg,
MineTypeEnum.Video_Ogg,
MineTypeEnum.Video_Quicktime,
MineTypeEnum.Video_Webm,
'video/x-msvideo',
'video/mp2t',
'video/3gpp2',

In ng-template doesn't accept variable

In ng-template if you put upload file , no problem but if you put {{ 'button.upload photo'|translate }} you see nothing, no button, no text, the button disappears.

Thanks

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

This repository currently has no open or pending branches.

Detected dependencies

None detected


  • Check this box to trigger a request for Renovate to run again on this repository

Pull and Publish

I think there are some interesting improvements on the @banksemi fork and I wanna ask if it is possible integrate it and when you publish an update on npm.
I really need the index.ts update because actually angular doesn't compile the library if I enable Ivy

Cannot read property 'nativeElement' of undefined - Angular 9

Upgraded an angular application to version 9 and this error shows from the ngx-upload library.

core.js:5882 ERROR TypeError: Cannot read property 'nativeElement' of undefined at InputfileComponent.push../node_modules/@wkoza/ngx-upload/__ivy_ngcc__/components/inputfile.component.js.InputfileComponent.ngOnInit (inputfile.component.js:32) at callHook (core.js:3941) at callHooks (core.js:3905) at executeInitAndCheckHooks (core.js:3846) at refreshView (core.js:11802) at refreshDynamicEmbeddedViews (core.js:13149) at refreshView (core.js:11807) at refreshComponent (core.js:13224) at refreshChildComponents (core.js:11515) at refreshView (core.js:11836)

Is the library officially supporting angular 9 yet ?

Mime type

Hi,

It is possible in ngx-upload to accept all types of files.

Thanks

Multiple and Accept inputs on the directive

I attempted to figure out how to add something like <input [multiple]="multiple" [accept]="accept"> to the directive so that those options can be set dynamically. Don't have much experience with component factories though. Is there a way to accomplish this? Thanks for the program!

Export all class

To build without error with Ivy, we need you export all the classes.

This is my error
image

Send the files outside form

Hi @wKoza,

I cannot use uploadAll. I don’t send a form but a class and I have to put the files in that class. I have seen the .file but I don’t have the image. I need an array equivalent to file but with the image. There is a way to do it from ngx-upload?

Thanks

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

Error on dependency injection

Hi!

I know, mantain angular8 with and without Ivy is an aweful work.

Now, with Ivy, library works like a charm.

But without Ivy this is the error in DI:

" Can't resolve all parameters for *Component in path: (?) "

Thumbnail access

Bonjour,

Hello mate, I'm using your amazing ngx-upload package. Can you help me with a question?

I'm trying to get the thumbnail back from the events to be able to emit it to my parent component.

Is it possible to do?

By the way, I tried to send you a message from your web site, but it doesn't work.

Is it possible to override the UploadOptions in a Component?

I need override the UploadOptions

const uploadOptions: UploadOptions = { method : 'POST', url: 'your_backend_upload_url', httpStrategy: HttpClientUploadService };

NgxUploadModule.forRoot(uploadOptions, ngxDropTargetOptions)

Like DropTargetOptions
[ngxDragAndDrop]="options"

Error: Can't resolve all parameters for InputfileComponent: ([object Object], ?, [object Object], [object Object], [object Object])

Hello William,

I am getting an error: compiler.js:2427 Uncaught Error: Can't resolve all parameters for InputfileComponent: ([object Object], ?, [object Object], [object Object], [object Object]).

angular verison: "~7.1.0",
ngx-upload version: ^8.0.0-beta.0

app.module.ts

import { DropTargetOptions, NgxUploadModule} from '@wkoza/ngx-upload';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    BrowserAnimationsModule,
    AppRoutingModule,
    NgxUploadModule.forRoot(),
  ],
  providers: [AppUrlService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html

<form #ourForm="ngForm"> or via a simple button-like : <span class="btn btn-outline-success btn-s" *ngxInputFile="optionsInput">Upload local files</span> </form>

app.component.ts

@ViewChild('ourForm') ourForm;

optionsInput: InputFileOptions = {
  multiple: false,
  accept: [MineTypeEnum.Image]
};

constructor(
  private uploader: HttpClientUploadService
) { }

ngOnInit() {
  this.uploader.queue = [];

  // upload  files
  this.uploader.onCancel$.subscribe(
          (data: FileItem) => {
              console.log('file deleted: ' + data.file);

          });

      this.uploader.onProgress$.subscribe(
          (data: any) => {
              console.log('upload file in progree: ' + data.progress);

          });

      this.uploader.onSuccess$.subscribe(
          (data: any) => {
              console.log(`upload file successful:  ${data.item} ${data.body} ${data.status} ${data.headers}`);

          }
      );
}

Possibility of (fileSelected) event on ngxDragAndDrop

Hi, is there any possibility of adding some helper outputs like fileSelected on ngxDragAndDrop?

Assume that I have one form with 2 instances of fileSelect:

       <div
        class="my-drop-zone"
        ngxDragAndDrop
        *ngxInputFile>
        <span class="__drop-text">Click to select...</span>
      </div>
       <div
        class="my-drop-zone"
        ngxDragAndDrop
        *ngxInputFile>
        <span class="__drop-text">Click to select...</span>
      </div>

and I want to store my files in the file queue by keys like:

coverImage: [ FILE ]

gallery: [ FILE, FILE, FILE ]

only available available this._uploader.onAddToQueue$ listens to queue without the option to focus on a single file drop or select.

Would be great to have something like:

       <div
        class="my-drop-zone"
        ngxDragAndDrop
        *ngxInputFile
       (fileSelected)="addToQueue({ key: 'coverImage', file: $event })">
        <span class="__drop-text">Click to select...</span>
      </div>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.