在使用angular时,想要使用<input type="file" />来选择本地文件,并获取文件的内容,比如名字、大小等。这时候就需要在input中添加change事件来监听input的变化,具体如下:
app.component.html:
<input type="file" class="file" (change)=getFile($event) />
app.component.ts:
public name:any = '';//保存文件名
public size:any = '';//保存文件大小
getFile(e){
let files = e.target.files[0];
this.name = files.name;
this.size = Math.floor(files.size / 1024) + 'kb';//file的文件大小单位是字节,除以1024就是kb,然后向下取整
};
如果想要将文件的内容输出在页面,直接使用双向数据绑定即可。