Giter Site home page Giter Site logo

stantoxt / ngx-uploadx Goto Github PK

View Code? Open in Web Editor NEW

This project forked from kukhariev/ngx-uploadx

0.0 1.0 0.0 2.77 MB

Angular Resumable Upload Module

License: MIT License

TypeScript 82.53% JavaScript 8.10% HTML 6.86% SCSS 2.23% PowerShell 0.16% Shell 0.11%

ngx-uploadx's Introduction

ngx-uploadx

Angular Resumable Upload Module

npm version Build status commits since latest release

Key Features

  • Pause / Resume / Cancel Uploads
  • Retries using exponential back-off strategy
  • Chunking

Basic usage

  • Add ngx-uploadx module as dependency:
  npm install ngx-uploadx
  • Import UploadxModule:
//...
import { UploadxModule } from 'ngx-uploadx';

@NgModule({
  imports: [
    UploadxModule,
   // ...
});
  • Add uploadx directive to the component template and provide the required options:
// Component code
//...
import { UploadxOptions, UploadState } from 'ngx-uploadx';

@Component({
  selector: 'app-home',
  templateUrl: `
  <input type="file" [uploadx]="options" (state)="onUpload($event)">
  `
})
export class AppHomeComponent {
  options: UploadxOptions = { endpoint: `[URL]` };
  onUpload(state: UploadState) {
    console.log(state);
    //...
  }
}

Please navigate to the src/app sub-folder for more detailed examples

Server-side setup

API

UploadxOptions

  • allowedTypes Allowed file types (directive only)

  • authorize Function used to authorize requests (example)

  • autoUpload Auto start upload when files added. Default value: true

  • storeIncompleteUploadUrl Keep an incomplete upload URL to allow resuming after browser restart. Default value: true

  • chunkSize Fixed chunk size. If not specified, the optimal size will be automatically adjusted based on the network speed. If set to 0, normal unloading will be used instead of chunked.

  • maxChunkSize Dynamic chunk size limit

  • concurrency Set the maximum parallel uploads. Default value: 2

  • endpoint URL to create new uploads. Default value: '/upload'

  • headers Headers to be appended to each HTTP request

  • metadata Custom metadata to be added to the uploaded files

  • multiple Allow selecting multiple files. Default value: true (directive only)

  • prerequest Function called before every request (example)

  • retryConfig Object to configure retry settings:

    • maxAttempts Maximum number of retry attempts. Default value: 8
    • shouldRestartCodes Upload not exist and will be restarted. Default value: [404, 410]
    • authErrorCodes If one of these codes is received, the request will be repeated with an updated authorization token . Default value: [401]
    • shouldRetryCodes Retryable 4xx status codes. Default value: [423, 429]
    • shouldRetry Overrides the built-in function that determines whether the operation should be retried
    • minDelay Minimum (initial) retry interval. Default value: 500
    • maxDelay Maximum retry interval. Default value: 50_000
    • onBusyDelay Delay used between retries for non-error responses with missing range/offset
    • timeout Time interval after which unfinished requests must be retried
  • token Authorization token as a string or function returning a string or Promise<string>

  • uploaderClass Upload API implementation. Built-in: UploaderX(default), Tus. More examples.

UploadxModule

Adds directives and provide static method withConfig for global configuration (example)

Directives

<div uploadxDrop>
  <label class="file-drop">
    <input type="file" [uploadx]="options" [control]="control" (state)="onState($event)" />
  </label>
</div>

uploadx

File input directive

selectors: [uploadx], uploadx

Properties:

  • @Input() uploadx: UploadxOptions Set directive options

  • @Input() options: UploadxOptions Alias for uploadx property

  • @Input() control: UploadxControlEvent Control the uploads

  • @Output() state: EventEmitter<UploadState> Event emitted on upload state change

uploadxDrop

File drop directive.

selector: uploadxDrop

Activates the .uploadx-drop-active class on DnD operations.

UploadxService

  • init(options?: UploadxOptions): Observable<UploadState>

    Initializes service. Returns Observable that emits a new value on progress or status changes.

    //  @example:
    uploadxOptions: UploadxOptions = {
      concurrency: 4,
      endpoint: `${environment.api}/upload`,
      uploaderClass: Tus
    };
    ngOnInit() {
      this.uploadService.init(this.uploadxOptions)
        .subscribe((item: UploadState) => {
          console.log(item);
          // ...
        }
    }
  • connect(options?: UploadxOptions): Observable<Uploader[]>

    Initializes service. Returns Observable that emits the current queue

    // @example:
    @Component({
      template: `
        <input type="file" uploadx">
        <div *ngFor="let item of uploads$ | async">{{item.name}}</div>
      `,
      changeDetection: ChangeDetectionStrategy.OnPush
    })
    export class UploadsComponent {
      uploads$: Observable<Uploader[]>;
      options: UploadxOptions = {
        endpoint: `${environment.api}/upload?uploadType=uploadx`,
        headers: { 'ngsw-bypass': 1 }
      }
      constructor(private uploadService: UploadxService) {
        this.uploads$ = this.uploadService.connect(this.options);
      }
  • disconnect(): void

    Terminate all uploads and clears the queue

  • handleFiles(files: FileList | File | File[], options = {} as UploadxOptions): void

    Creates uploaders for files and adds them to the upload queue

  • control(event: UploadxControlEvent): void

    Uploads control

    // @example:
    pause(uploadId: string) {
      this.uploadService.control({ action: 'pause', uploadId });
    }
    setToken(token: string) {
      this.uploadService.control({ token });
    }
  • request<T = string>(config: AjaxRequestConfig): Promise<AjaxResponse<T>>

    Make HTTP request with axios like interface.

  • queue: Uploader[]

    Uploaders array

  • events: Observable<UploadState>

    Uploads state events

DI tokens

  • UPLOADX_FACTORY_OPTIONS for override default configuration

  • UPLOADX_OPTIONS for global options

  • UPLOADX_AJAX for override internal ajax lib

Run demo

  • Run script npm start
  • Navigate to http://localhost:4200/

Build

Run npm run build to build the lib.

packaged by ng-packagr

Contributing

Pull requests are welcome!

References

License

The MIT License (see the LICENSE file for the full text)

ngx-uploadx's People

Contributors

kukhariev avatar maertz avatar philippjenni avatar renovate-bot avatar renovate[bot] avatar smartm0use avatar

Watchers

 avatar

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.