Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

angular-file

ackerapple44.3kMIT4.0.2TypeScript support: included

Easy to use Angular directives for user file selections

Angular, ng files, file-upload, ng-file-upload, ng2-file-upload, angular-file-upload

readme

angular-file

Easy to use Angular directives for user file selections (DEMO PAGE)

hire me npm version npm downloads Dependency Status Build status Build Status min size minzip size

This package is to handle select/drag/drop of files. Once files are selected, for uploading, you then use Angular's @angular/common/http for uploading selected files (see here for more on uploading).

<summary>Table of Contents</summary>

Quick Start

  1. A recommended way to install angular-file is through npm package manager using the following command:

    npm install angular-file --save-dev

    Alternatively, you can download it in a ZIP file.

  2. Currently angular-file contains three directives: ngf, ngfSelect, and ngfDrop. ngf and ngfSelect are quite the same with just different defaults and they both utilize <input type="file" /> functionality. ngfDrop is used to designate an area that will be used for dropping of file(s).

  3. More information regarding using of angular-file is located in demo and demo sources.

Examples

Practical Example

An example intended to have every line needed to run an app with angular-file. To use this example, replace the contents of main.ts with this code, and add <app></app> to the body of index.html

import { ngfModule, ngf } from "angular-file"
import { Component, NgModule } from "@angular/core"
import {
  HttpClient, HttpClientModule, HttpRequest, HttpResponse, HttpEvent
} from "@angular/common/http"
import { platformBrowserDynamic } from "@angular/platform-browser-dynamic"
import { BrowserModule } from '@angular/platform-browser'
import { Subscription } from 'rxjs'

// two ways to upload files
const template = `
<input
  ngf
  multiple
  type      = "file"
  accept    = "image/*"
  [(files)] = "files"
  maxSize   = "1024"
  capturePaste = "1"
/>
<button *ngIf="files" (click)="uploadFiles(files)">send files</button>

<ngfFormData
  [files]      = "files"
  [(FormData)] = "myFormData"
  postName     = "file"
></ngfFormData>

<ngfUploadStatus
  [(percent)] = "uploadPercent"
  [httpEvent] = "httpEvent"
></ngfUploadStatus>

<div *ngIf="uploadPercent">
  Upload Progress: {{ uploadPercent }}%
</div>
`

@Component({
  selector: 'app',
  template: template
})
export class AppComponent {
  postUrl = '...'
  myFormData:FormData//populated by ngfFormData directive
  httpEvent:HttpEvent<{}>

  constructor(public HttpClient:HttpClient){}

  uploadFiles(files:File[]) : Subscription {
    const config = new HttpRequest('POST', this.postUrl, this.myFormData, {
      reportProgress: true
    })

    return this.HttpClient.request( config )
    .subscribe(event=>{
      this.httpEvent = event

      if (event instanceof HttpResponse) {
        alert('upload complete, old school alert used')
      }
    },
    error=>{
      alert('!failure beyond compare cause:' + error.toString())
    })
  }
}

@NgModule({
  imports: [
    BrowserModule,
    HttpClientModule,
    ngfModule
  ],
  declarations: [
    AppComponent
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

platformBrowserDynamic().bootstrapModule(AppModule);

Select Files Examples

Examples of how to allow file selection

Multiple

<input type="file" ngf [(files)]="files" multiple  />

Single

<input type="file" ngf [(file)]="file" />

Element

<div ngfSelect multiple="1" [(files)]="files">
  Tap to Select
</div>

Image Backgrounds Only

<button ngfSelect [(file)]="userFile" accept="image/*" multiple="1">
  Tap to Select
</button>
<div [ngfBackground]="userFile"
  style="background-size:cover;background-repeat:no-repeat;width:50px;height:50px"
></div>

Images Only

<button ngfSelect [(file)]="userFile" accept="image/*" multiple="1">
  Tap to Select
</button>
<img [ngfSrc]="userFile" />

Drop Files Examples

Examples of how to allow file drag/drop

Basic

<div ngfDrop
  [(files)]="files"
  [(file)]="file"
  ([validDrag])="validDrag"
  ([invalidDrag])="invalidDrag"
  [ngClass]="{'myHoverClass': validDrag, 'myAntiHoverClass': validDrag}"
>
  Drop Files Here
</div>

Combo Drop Select

<div ngfDrop selectable="1" multiple="1"
  [(files)]="files"
  [(validDrag)]="validComboDrag"
  [(invalidDrag)]="invalidComboDrag"
  [ngClass]="{'goodDragClass':validComboDrag, 'badDragClass':invalidComboDrag}"
>
  Combo drop/select zone
</div>

API

ngf Directive

A base directive that provides abilities of ngfDrop and ngfSelect. Does not auto default nor auto host element events like hover/drag/drop (see ngfDrop and/or ngfSelect)

ngf                 : ngf // reference to directive class
[multiple]          : string
[accept]            : string
[maxSize]           : number // bytes . 1024 = 1k . 1048576 = 1mb
[ngfFixOrientation] : boolean = true
[fileDropDisabled]  : any = false
[selectable]        : any = false
[(lastInvalids)]    : {file:File,type:string}[] = []
[(lastBaseUrl)]     : string // Base64 od last file uploaded url
[(file)]            : File // last file uploaded
[(files)]           : File[]
(init)              : EventEmitter<ngf>
[capturePaste]      : boolean // listen to window paste event for files
(fileSelectStart)   : EventEmitter<Event> // Event fired for user selecting files starting

ngfDrop Directive

Extends ngf and then auto hosts element event watching of hover/drag/drop

[fileDropDisabled]  : any = false
(fileOver)      :EventEmitter<any> = new EventEmitter()
[(validDrag)]   :any = false
[(invalidDrag)] :any = false

Supporting Internet Explorer 11 or less?

Only (fileOver) works accurately [(validDrag)] & [(invalidDrag)] should NOT be used as IE11 does not indicate the number of files NOR the types of files being dragged like other modern web browsers

ngfSelect Directive

Extends ngf and auto engages click base file selecting

[selectable]:any = true

ngfBackground Directive

[ngfBackground]:File

ngfSrc Directive

[ngfSrc]:File

ngfUploadStatus Directive

Does calculations of an upload event and provideds percent of upload completed

[(percent)]:number
[httpEvent]:Event

ngfFormData Directive

Converts files to FormData

[files]:File[]
[postName]:string = "file"
[fileName]:string//optional force file name
[(FormData)]:FormData

Uploading

Angular, natively, makes uploading files so very easy!

Did you know?

  • You do NOT and should NOT use a seperate package to upload files other than @angular/common
  • You do not need a package like ng2-file-upload which have outdated non-core-community driven file uploading scripts
  • Just can just use @angular/common to send files! Why add more unneccessary weight of dependency of another package?
  • Multi file uploading is so easy with @angular/common
  • You will have the most control seperating your file selecting from file uploading
  • You should use this package, angular-file, to select files and then give to Angular to upload

Uploading files is as easy as:

import { Subscription } from "rxjs"//only included for data typing
import {
  HttpClient, HttpRequest, HttpResponse
} from "@angular/common/http"

export const uploadFiles(files:File[]) : Subscription {
  const postUrl = "..."
  const myFormData:FormData = new FormData()

  files.forEach(file=>myFormData.append("file", file, "file-name.xyz"))

  const config = new HttpRequest("POST", postUrl, myFormData), {
    reportProgress: true
  })

  return this.HttpClient.request( config )
  .subscribe(event=>{
    if (event instanceof HttpResponse) {
      alert('upload complete, old school alert used')
    }
  },
  error=>{
    alert('!failure cause:' + error.toString())
  })
}

Troubleshooting

Please follow this guidelines when reporting bugs and feature requests:

  1. Use GitHub Issues board to report bugs and feature requests (not our email address)
  2. Please always write steps to reproduce the error. That way we can focus on fixing the bug, not scratching our heads trying to reproduce it.

Thanks for understanding!

Development

Work on this package

Source files are on not the default github branch

git clone https://github.com/AckerApple/angular-file.git -b development

Credits

  • Current Author: Acker Apple
  • Forked from outdated package: ng2-file-upload

License

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

changelog

angular-file - Change Log

All notable changes to this project will be documented here.

4.0.0 - (2023-05-16)

  • Built on Angular 14

3.9.3 - (2023-05-03)

  • Built with altered tsconfig.json

3.9.0 - (2023-05-03)

  • Built on Angular 13

3.8.0 - (2023-05-03)

  • Built on Angular 12

3.7.0 - (2023-05-03)

  • Reflect more accurate typing of file not being defined by default

3.6.0 - (2021-05-10)

  • Issue #98 fixed by PR #99 for this.fileElm was actually targeting the label wrapper
    • angular-file places a label wrapping a file on html and when saved to memory label targeted and not file input

3.5.3 - (2021-04-26)

  • Fix 3.5.0 variable references and possible undefined error

3.5.0 - (2021-04-22)

  • Close #27 regarding click to upload same file twice
    • ngOnChanges is listened to for when files or file is dropped then file input elm cleared
  • Dependencies updated
  • Demo updated with clear buttons next to inputs
  • Added (fileSelectStart) output event

3.4.0 - (2021-01-05)

  • Restructure things done in 3.3.1

3.2.3 - (2020-11-11)

  • Built with ng10
  • new [capturePaste] window event listener for files (default off)
  • selectable attribute now reads string values of 'false', 'null', '0' as false

3.1.1 - (2020-06-10)

  • Published version to npm
  • Includes touch fix error for Chrome Mobile

3.1.0 - (2020-06-10)

  • Build using @angular/cli library

3.0.1 - (2019-03-17)

  • fix typo

3.0.0 - (2019-02-01)

  • Built on Angular 9

2.0.0 - (2019-11-04)

  • built for dist better
  • built for ivy

1.3.1 - (2019-06-27)

  • Built on ng8
    • NOTE: A report from another package on ng8 claims may not be compatible with ng7
  • Built with strict mode
  • Fixed demo upload url
  • Fixed testing enviroment
  • Docs have bundle sizes

1.2.4 - (2019-06-26)

  • updated docs
  • removed peer dependencies
  • moved some dependencies into devDependencies

1.2.3 - (2019-05-22)

1.2.1 - (2019-05-20)

  • Adjust processing events into files

1.2.0 - (2019-05-16)

  • Updated to latest Angular
  • Demo has bundle stats
  • Removed legacy build techniques
  • Updated from angular-cli.json to angular.json

1.1.1 - (2019-04-04)

  • Added ngfSrc

1.1.0 - (2019-02-13)

  • Fixed fileDropDisabled binding
  • Docs to clarify ngf versus ngfDrop versus ngfSelect

1.0.2 - (2019-02-13)

1.0.0 - (2019-02-11)

  • strict mode on
  • check file type before file size
  • [(ref)] bindings have been removed from all components/directives
    • no more [(ngf)]
    • no more [(ngfSelect))]
    • use template references if needed: <input #ngfSelect="ngfSelect" ngSelect />

0.5.9 - (2018-12-04)

  • documentation

0.5.4 - (2018-04-21)

  • Fix file check when no files defined

0.5.2 - (2018-04-21)

  • Fix single file reselect after item removed from files

0.5.0 - (2018-02-07)

  • Removed much unused code from original package that this is a fork from
  • Fixed and ensured accept attribute working correctly
  • Improved demo page in terms of the accept attribute and file drag metadata
  • BREAKING CHANGES
    • Removed directive ngfUploader
    • ngfUploader.directive.ts has been removed from this package
    • FileUploader.class.ts has been removed from this package
    • FileUploader.class has been removed from this package
    • FileItem.class has been removed from this package
    • FileLikeObject.class has been removed from this package
    • Files are always considered valid when dragged inside browsers that dont allow ANY drag file metadata
    • Input forceFilename has been removed from all ngf directives
    • Input forcePostname has been removed from all ngf directives

[0.4.0] - (2017-12-05)

  • BREAKING CHANGES
    • Angular 4 updated to 5.0.5
      • Expected this package will require Angular5+
    • Updated every dependency

[0.3.8] - 2017-11-27

  • made accept and maxSize update on change

[0.3.7] - 2017-11-03

  • added ngfFormData directive

[0.3.6] - 2017-10-26

  • case-insensative accept filtering

[0.3.5] - 2017-10-25

  • Ensured accept filters transmit file names when possible for better mime type checking

[0.3.4] - 2017-10-24

  • enhanced acceptFilter filter checking

[0.3.3] - 2017-10-02

  • fixed IE11 dragdrop issue

[0.3.0] - 2017-10-02

Breaking Changes

  • [(files)] is now a default blank array . May cause issues if you have *ngIf="files" instead of *ngIf="files.length"
  • removed useNgHttp from ngfUploader and no longer depend on angular/http
  • ngf, ngfSelect, and ngfDrop no longer reset the [(files)]. They always append new files

    Added

  • ngfUploadStatus

[0.2.0] - 2017-10-02

Breaking Changes

  • FileUploader isHtml5Mode has been removed

    Added

  • ngfUploader

[0.1.0] - 2017-08-31

Breaking Changes

  • fileUrl is now lastBaseUrl

[0.0.0] - 2017-08-31

Overhauled by Acker

  • Taken from an outdated barely usable package to an up-to-date slimmed down easier to develop version

    Added

  • uploader.getFormData()