I want get the file name from my html input tag in a modal view and save it using Angular2. Can someone help me?
Asked
Active
Viewed 4.4k times
6 Answers
36
You can do next:
HTML:
<input type="file" (change)="fileEvent($event)" />
TypeScript:
fileEvent(fileInput: Event){
let file = fileInput.target.files[0];
let fileName = file.name;
}

mvermand
- 5,829
- 7
- 48
- 74

Igor Janković
- 5,494
- 6
- 32
- 46
-
and how to get file ext? – Shreyas Pednekar Aug 14 '18 at 05:19
-
5For those getting ```Property 'files' does not exist on type 'EventTarget'``` check https://stackoverflow.com/a/44932086/4281182 – Selçuk Cihan Apr 24 '19 at 09:28
-
i'm getting filename undefined. – jukebox Jun 06 '19 at 10:38
-
1@SelçukCihan Thanks mate. Your comment saves my life. – James Rao Jul 19 '19 at 12:30
3
You can try a more elegant option:
HTML:
<input #file type="file" (change)="updateFile(file)">
Script:
updateFile(file: HTMLInputElement) {
let name = file.value;
}

Sergey Dzyuba
- 96
- 3
3
HTML
<button (click)="imgFileInput.click()">Add</button>
{{ imgFileInput?.files[0]?.name }}
<input hidden type="file" #imgFileInput (change)="uploadSingle($event)"/>
Component
uploadSingle(event) {
const fileName = event.target.files[0].name;
}

Stepan Prokopiak
- 41
- 1
- 4
-
Please explain your lines of code so other users can understand its functionality. Thanks! – Ignacio Ara May 31 '18 at 07:46
-
This is totally unnecessary. A label with the for attribute will do the job without catching any clicks. Also I'm not completely sure you can trigger a click on a hidden element. – Sampgun Feb 19 '19 at 16:30
1
HTML
<input type="file" (change)="onFileChange($event)">
Script
onFileChange(event) {
let files = event.target.files[0].name;
}

Vivek Singh
- 1,113
- 10
- 20
-
1
-
1You can', It's a security feature in modern browsers. this can help, https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file – Vivek Singh Dec 12 '17 at 09:57
1
This work form me:
HTML
<input type="file" (change)="detectFiles($event)">
<div class="output">Seleccionado: {{ fileName }} </div>
TS
selectedFiles: FileList;
fileName: string;
detectFiles(event) {
this.selectedFiles = event.target.files;
this.fileName = this.selectedFiles[0].name;
console.log('selectedFiles: ' + this.fileName );
}

Alvargon
- 324
- 3
- 10
0
This link's https://stackoverflow.com/a/44932086/4281182 solution suggested by @ Selçuk Cihan did not help so my workaround was to make the fileInput param type "any" by doing this
fileEvent(fileInput){
let file = fileInput.target.files[0];
let fileName = file.name;
}
so in TS runtime this is a pure JS code
Anyways thanks for this great ans it saved me a lot of time

Mohammed Yousif
- 1
- 1