前端使用input
//注意这里不要用<input></input>,会报错,直接用<input />
<Input type="file" accept='text/plain' onChange={this.readFile.bind(this)} />
函数:
readFile(e: any) {
const reader = new FileReader();
let input = e.target.files[0];//文件
reader.readAsText(input);//text读取,这里看文件类型
reader.onload = function (e: { target: { result: any; }; }) {
let text = e.target.result;//文件内容
let arr = (text as string).split("\n");//切分
let newArr = arr.filter(i => i && i.trim())//删除空行,空格等
let item = {
uid: uuidv1(),
name: input.name,
text: newArr
}
let list = this.state.fileList;
list.push(item);
this.setState({ fileList: list });
}.bind(this);//后面bind才能setState
}