简体   繁体   中英

Angular 2 (change) for file upload

I am using the Angular 2 (change) to detect the uploaded file and trigger the function. But I am facing the problem when I tried to upload the same file again, as there is no change in the file, (change) is not triggered. Please suggest the event binding in this case.

<input type="file" name="file" id="fileupload" (change)="onChange($event)"/>

Is there any way to reset the input value of type file to empty.

You can access the file input as a ViewChild and get the files from it.

import { Component, ViewChild, ElementRef} '@angular/core';
@Component({
//...
template: `
  <input #fileInput type='file' (change)="fileChanged($event)">
`
//...
})
export class FileInputComponent {
  @ViewChild('fileInput') myFileInput: ElementRef;

  getFileLater() {
    console.log(this.myFileInput.nativeElement.files[0]);
  }

  fileChanged(event) {
    console.log(event.target.files[0]);
  }
}

.files[] on the nativeElement is always an array even if there is only one file selected (or none, for that matter). It will give you file objects exactly as it would if you accessed event.target.files from the (change) event so you can do with them what you want after the fact.

It should be mentioned though that when a file is chosen on the file input and the change event is triggered, the file hasn't actually been 'uploaded' anywhere. It just passes the browser a reference to it (with some other meta data) that the client can work with. Actually uploading the files is something you have to program in separately.

UPDATE:

In order to force the file input to fire the change event even when choosing a file that was previously selected, the file input has to be reset by clearing its value whenever the Browse button is clicked. Since you're already using jQuery, you can do that like so: $('#fileupload').val(""); .

See my forked Plunker for a working example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM