Home

Awesome

Looking for the changelog?

(Versions of this package < 2.0.1) If you see an error about an unknown token { with some imports.

This isn't compatible with Angular Universal (Server side rendering) yet. I'll fix this in a future release. Until then, if you need to server-side render this package, please refer to the instructions here. Summarized below:

FileInputAccessor

Adds Reactive and Template behavior you're used to using with Angular Forms, but for <input type="file">. Check out the demo to see it in action.

Sample code for sending the files from Angular to your backend is further down this page.

Provides NG_VALUE_ACCESSOR implementing the ControlValueAccessor interface. For more info, refer to this stack overflow answer linked on this issue.

Which version should I use?

Version 1.x.x uses Rxjs v5.5.x. Rxjs v6 underwent some changes that include adjustments to the way operators are imported along with other breaking changes.

Version 2.x.x uses Rxjs v6. If you're interested in updating your projects, a package has been created for that very purpose by the Rxjs team.

As a general rule:

RxJS

RxJS docs (beta as of 2018/05/05). Another very helpful resource to familiarize yourself with Rxjs by providing a list of commonly used operators with examples.

Using with your forms

  1. Install package from npm

    npm i file-input-accessor

  2. Import the FileInputAccessorModule.

     import {BrowserModule} from '@angular/platform-browser';
     import {FileInputAccessorModule} from "file-input-accessor";
    
     @NgModule({
         declarations: [
             AppComponent
         ],
         imports: [
             BrowserModule,
             FileInputAccessorModule
         ],
         providers: [],
         bootstrap: [AppComponent]
     })
     export class AppModule {}
    
  3. That's it. You can use FormControl and NgModel with your file input.

     <!--file-upload.component.html-->
    
     <form>
       <!--Reactive form control-->
       <input type="file" multiple [formControl]="fileControl">
     </form>
    
     <form>
       <!--Template form control, using model changes to trigger upload-->
       <input type="file" multiple name="templateFileUploadControl" [ngModel]="modelChangesFiles" (ngModelChange)="onFileInputChange($event)">
     </form>
    
     <form>
       <!--Template form control, upload is manually triggered-->
       <input type="file" multiple [(ngModel)]="manualChangesFiles" name="templateFileUploadControl2">
       <button type="button" (click)="submitFiles()">Click to upload</button>
     </form>
    

Uploading the files

  1. Import the HttpClientModule if it isn't already.

     @NgModule({
         declarations: [
             AppComponent,
             FileUploadComponent
         ],
         imports: [
             BrowserModule,
             RouterModule.forRoot(ROUTES),
             HttpClientModule,
             FileInputAccessorModule
         ],
         providers: [],
         bootstrap: [AppComponent]
     })
     export class AppModule {
     }
    
  2. When you're ready to upload your files, append them to your FormData and use HttpClient to call your file upload endpoint.

     @Component({
         selector: 'app-file-upload',
         templateUrl: './file-upload.component.html',
         styleUrls: ['./file-upload.component.css']
     })
     export class FileUploadComponent implements OnInit {
    
         fileControl = new FormControl();
    
         modelChangesFiles: ICustomFile[] = [];
         manualChangesFiles: ICustomFile[] = [];
    
         constructor(private _http: HttpClient) {
         }
    
         /**
          * Subscribe to the valueChanges Observable on the reactive FormControl.
          */
         ngOnInit() {
             this.fileControl.valueChanges
                 .pipe(mergeMap(files => this.uploadFiles(files)))
                 .subscribe(() => this.fileControl.setValue([]));
         }
    
         /**
          * (ngModelChange) event handler
          *
          * @param {ICustomFile[]} event
          */
         onFileInputChange(event: ICustomFile[]) {
             this.uploadFiles(event)
                 .subscribe(() => (this.modelChangesFiles = []));
         }
    
         /**
          * Upload button's (click) event handler
          */
         submitFiles() {
             this.uploadFiles(this.manualChangesFiles)
                 .subscribe(() => (this.manualChangesFiles = []));
         }
    
         /**
          * Appends the provided files to FormData and returns an Observable that will pass the FormData
          * to the api when subscribed.
          *
          * @param {ICustomFile[]} files
          * @returns {Observable<Object>}
          */
         private uploadFiles(files: ICustomFile[]): Observable<Object> {
             if (!files || files.length === 0) {
                 return EMPTY;
             }
    
             const data = new FormData();
    
             for (const file of files) {
                 data.append('file', file.slice(), file.name);
             }
             return this._http.post('/api/files', data);
         }
     }
    

Validation

An async validator is included and only runs if sync validation passes and values are provided to the accessor inputs. The following errors may be set true on the control if at least one file fails validation:

Accessor Inputs

All inputs are optional.

ICustomFile

An interface implemented by the Files added to the control. All properties are optional and only present if withMeta input is set to true.