按钮操作打开文件对话框
<Button width={100}
text="导入Excel"
type="success"
stylingMode="contained"
className='bnt'
id={'open-file'}
onClick={() => {
//打开编写好文件选择对话框(函数)
this.openFilePicker({
fn: (event, files) => {
console.group("获取到的文件");
// console.log("files", files);
this.importExcel(files)//选择文件完后调接口
console.groupEnd();
},
accept: ".xls,.xlsx", // 直接在调用时设置
multiple: false // 如果不需要选择多个文件,可以显式设置
});
}}
/>
openFilePicker函数
// 一个异步函数openFilePicker,它接受一个对象作为参数,
async openFilePicker({fn, accept = '.xls,.xlsx', multiple = false}) {
const inpEle = document.createElement("input");// 创建一个新的 <input> 元素
inpEle.id = `__file_${Math.trunc(Math.random() * 100000)}`;//设置一个随机的ID,确保在DOM中是唯一的。
inpEle.type = "file";// 设置类型 file,这意味着它将被用作文件选择器。
inpEle.style.display = "none";//display'属性设置为’none',使其在页面上不可见
inpEle.accept = accept;//限制用户只能选择`.xls`或`.xlsx`类型的文件
inpEle.multiple = multiple; //false `multiple`属性为`true`,允许用户选择多个文件
/*
* 给<input>元素添加一个change事件监听器。当用户选择了文件后,会触发这个事件。
* 事件处理函数会调用传入的fn回调函数,并传入两个参数:event(事件对象)和event.target.files(一个FileList对象,包含了用户选择的所有文件)。
* {once: true}表示该监听器只会触发一次,之后会自动移除。
* */
inpEle.addEventListener("change", event => fn.call(inpEle, event, event.target.files), {once: true});
document.body.appendChild(inpEle); // 将 input 添加到 body,确保它可见
inpEle.click();
inpEle.remove(); // 触发点击后立即移除,避免留在DOM中
}
importExcet函数(调接口)
//导入excel(异步处理接口)
async importExcel(files) {
if (!files || files.length === 0) {
hsNotify.error('未选择文件');
return;
}
//创建一个新的 FormData 对象 formdata。FormData 对象用于通过
//XMLHttpRequest 或 fetch API 发送表单数据(以及文件)。
let formdata = new FormData();
formdata.append('file', files[0])//将用户选择的第一个文件添加到 formdata 对象中
const response = await importCustomerPlane(formdata);//使用 await 关键字调用
if (!response) {
hsNotify.error('导入失败')
return
}
if (response.code === 200) {
hsNotify.success(response.msg)//提示导入成功
//调列表(刷新)
this.getList()
} else {
hsNotify.error(response.msg)//提示导入失败
return
}
}