Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 576
Kiran Kumar Avatar asked Aug 26 '16 19:08

Kiran Kumar


People also ask

How can I limit the size of attachment file upload in angular?

You can restrict the maximum allowed file size (in bytes) by using the maxFileSize property. If the selected file exceeds the maximum size, an error message will be displayed.

How do I get real path instead of Fakepath?

Use IE with file protocol if you want to get the real path. Possible duplicate of How to get full path of selected file on change of <input type='file'> using javascript, jquery-ajax?

How can you tell if a file is canceled and clicked on input?

The easiest way is to check if there are any files in temporary memory. If you want to get the change event every time user clicks the file input you can trigger it. Show activity on this post. In my case i had to hide submit button while users were selecting images.


1 Answers

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.

like image 145
ABabin Avatar answered Sep 22 '22 00:09

ABabin