upload上传 file对象(.json文件)转为json对象
/**
* 将file对象(.json文件)转为json对象
* @param {File} file file对象
*/
function fileToJson(file: File) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e: any) => {
try {
const data = JSON.parse(e?.target?.result); // 解析成json对象
resolve(data);
} catch (err: any) {
reject(err);
}
}; // 成功回调
reader.onerror = (err) => {
reject(err);
}; // 失败回调
reader.readAsText(new Blob([file]), 'utf-8'); // 按照utf-8编码解析
});
}
const uploadProps = {
accept: '.json',
name: 'file',
beforeUpload: (file: File) => {
setUploadLoading(true);
fileToJson(file)
.then((itemInfo: any) => {
// TODO: 校验文件的合法性
// console.log('uploadVersionInfo', itemInfo);
const { queryResponse = {}, contentResponse = {}, knowledgeResponse = {} } = itemInfo;
setQueryDetail(queryResponse);
setGuideDetail(contentResponse);
setWikipediaDetail(knowledgeResponse);
})
.catch((err) => {
message.error('解析失败:' + err?.message);
});
setUploadLoading(false);
return Upload.LIST_IGNORE;
},
};
......
return {
<Upload {...uploadProps}>
<Button icon={<UploadOutlined />}>导入文件</Button>
</Upload>
}