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 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.
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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With