本功能基于antd pro项目,所以使用antd组件–upload
1.使用上传组件读取文件内容
html片段
<Upload beforeUpload={getTextInfo} showUploadList={false} >
<Button type='primary'>
<img src={importImg} style={{marginRight:10}} />
导入
</Button>
</Upload>
js片段
//导入txt文件
const getTextInfo=(file:any)=>{
//判断文件类型
if (file.type !== 'text/plain') {
message.error(`${file.name} 不是.txt文件!`);
return file.type === 'text/plain' ? true : Upload.LIST_IGNORE;
}
//导入条数
let importCount:any
//读取内容
let targetNum:any
const reader=new FileReader();
reader.readAsText(file,"UTF-8");
reader.onload=async (result:any)=>{
targetNum=result.target.result;
//将读取的内容传给后台,得到后台返回的增加了多少条,然后通过计算,跳到最后一页
importCount=await onImport(targetNum)
if(importCount>0){
importSuc(importCount)
}
}
return false;
}
//导入
const onImport=async(str:any)=>{
const params={
current:1,
pageSize:10
}
const {errorCode,data,errorMessage}=await importPool(params,str)
if (!errorCode) {
message.success(errorMessage);
}
return data
}
接口
//导入
export async function importPool(params:any,str:any){
return await http.postTxt(ACTION.importPool,params,str)
}
http.ts
export const postTxt = async (action: string, params?: any,fileStr?:any) => {
const data = {
action,
params,
product: 'EMRQuality',
};
const dataStr=JSON.stringify(data)
const txtStr="-----------------------------8eb5b37251gef"+fileStr
const str=dataStr+txtStr
try {
const result = await request('/api/', { method: 'POST', data:str });
const { errorCode, errorMessage, showType, success } = result;
if (errorCode) {
if (showType === 1) {
message.warn(errorMessage);
} else if (showType === 2) {
message.error(errorMessage);
}
}
return { ...result, success: success === 'true' };
} catch (error) {
console.error(error);
}
};