核心法宝:FileReader
{
this.returnDomFun(
<>
<UploadFile
title={
'AAAA'}
fileName={
fileName}
onChangeInput={
(e) => this.inputName(`fileName`, e.target.value)}
onChange={
this.chengFileFun}
beforeUpload={
this.beforeUpload}
maxCount={
1}
action="#"
showUploadList={
false}
/>
<a href="#!" style={
{
color: 'red', fontSize: '12px', marginTop: '8px', lineHeight: "12px", marginLeft: '8px' }}>文件内容自动追加到下方表格</a>
</>
, {
width: "600px" })
}
我们只关注onChange事件即可,
chengFileFun = (filer) => {
let name = filer.file.name
//文件对象
let fileObj = filer.file
// 实例化FileReader对象
var reader = new FileReader();
// 正则校验
if (/text\/\w+/.test(fileObj.type)) {
reader.readAsText(fileObj.originFileObj);
// 读取失败自动触发
reader.onerror = function (event) {
message.warning("文件读取失败")
return false
};
// 读取完成触发
reader.onload = function () {
if (this.readyState === 2) {
let result = this.result.split("\r\n")
console.log(result, 'result')
}
}
}
this.setState({
fileName: name,
fileObj
})
}