Html 从输入类型文件 Angular2 中获取文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42481746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get file name from input type file Angular2
提问by Sandro De Marco
I want get the file name from my html input tag in a modal view and save it using Angular2. Can someone help me?
我想在模态视图中从我的 html 输入标签中获取文件名并使用 Angular2 保存它。有人能帮我吗?
回答by Igor Jankovi?
You can do next:
您可以执行以下操作:
HTML:
HTML:
<input type="file" (change)="fileEvent($event)" />
TypeScript:
打字稿:
fileEvent(fileInput: Event){
let file = fileInput.target.files[0];
let fileName = file.name;
}
回答by Sergey Dzyuba
You can try a more elegant option:
您可以尝试更优雅的选择:
HTML:
HTML:
<input #file type="file" (change)="updateFile(file)">
Script:
脚本:
updateFile(file: HTMLInputElement) {
let name = file.value;
}
回答by Stepan Prokopiak
HTML
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;
}
回答by Alvargon
This work form me:
这项工作形成了我:
HTML
HTML
<input type="file" (change)="detectFiles($event)">
<div class="output">Seleccionado: {{ fileName }} </div>
TS
TS
selectedFiles: FileList;
fileName: string;
detectFiles(event) {
this.selectedFiles = event.target.files;
this.fileName = this.selectedFiles[0].name;
console.log('selectedFiles: ' + this.fileName );
}
回答by Vivek Singh
HTML
HTML
<input type="file" (change)="onFileChange($event)">
Script
脚本
onFileChange(event) {
let files = event.target.files[0].name;
}
回答by Mohammed Yousif
This link's https://stackoverflow.com/a/44932086/4281182solution suggested by @ Sel?uk Cihan did not help so my workaround was to make the fileInput param type "any" by doing this
这个链接的https://stackoverflow.com/a/44932086/4281182由@ Sel?uk Cihan 建议的解决方案没有帮助,所以我的解决方法是通过这样做使 fileInput 参数类型为“any”
fileEvent(fileInput){
let file = fileInput.target.files[0];
let fileName = file.name;
}
so in TS runtime this is a pure JS code
所以在 TS 运行时这是一个纯 JS 代码
Anyways thanks for this great ans it saved me a lot of time
无论如何,感谢这个伟大的人,它为我节省了很多时间