Get file name from input type file Angular2

2020-07-03 04:55发布

I want get the file name from my html input tag in a modal view and save it using Angular2. Can someone help me?

6条回答
Juvenile、少年°
2楼-- · 2020-07-03 05:19

HTML

<input type="file" (change)="onFileChange($event)">

Script

onFileChange(event) {    
     let files = event.target.files[0].name;
}
查看更多
SAY GOODBYE
3楼-- · 2020-07-03 05:31

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;
}
查看更多
啃猪蹄的小仙女
4楼-- · 2020-07-03 05:32

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;
}
查看更多
该账号已被封号
5楼-- · 2020-07-03 05:33

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

查看更多
虎瘦雄心在
6楼-- · 2020-07-03 05:37

You can try a more elegant option:

HTML:

<input #file type="file" (change)="updateFile(file)">

Script:

updateFile(file: HTMLInputElement) {
  let name = file.value;
}
查看更多
我只想做你的唯一
7楼-- · 2020-07-03 05:37

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 );
  }
查看更多
登录 后发表回答