导入
1、api链接
introductionCarModelInfoApi='/carModel/info/introductionCarModelInfo',
2、接口操作
export function importExcel(data: any) {
return new Promise(async () => {
const { createMessage ,createConfirm} = useMessage();
const formData = new FormData();//转换fromData格式
formData.append('file', data);//传给后端的参数,
defHttp
.request(
{
url: `/af-zk-carmodel${Api.introductionCarModelInfoApi}`,
method: 'post',
params: formData,
},
{
isTransformRequestResult: false,//框架配置 用于页面代码可能需要直接获取code,data,message这些信息时开启
apiUrl: import.meta.env.DEV ? '/basic-api/af' : '',
}
)
.then((res) => {
if (res.data.code=== '000000') {
// createMessage.success('数据传输完成,请稍后重新查询列表数据');
createConfirm({
iconType: 'success',
content: `成功${res.data.data.successNum}条,失败${res.data.data.defaltNum}条`,
});
} else {
createMessage.error('导入失败,请稍后再试');
}
});
});
}
3、自己封装的上传方法,引入到使用的页面直接调用标签
<template>
<div style="display: inline">
<input
ref="inputRef"
type="file"
v-show="false"
accept=".xlsx, .xls"
@change="handleInputClick"
/>
<div @click="handleUpload" style="display: inline">
<slot></slot>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent, ref, unref } from 'vue';
export default defineComponent({
name: 'ImportExcel',
emits: ['success', 'error'],
setup(_, { emit }) {
const inputRef = ref<HTMLInputElement | null>(null);
const loadingRef = ref<Boolean>(false);
/**
* @description: 把excel数据转换成formData
*/
function readerData(rawFile: File) {
loadingRef.value = true;
return new Promise((resolve, reject) => {
let formData = new FormData();
formData.append('file', rawFile);
try {
emit('success', formData);
resolve('');
} catch (error) {
reject(error);
emit('error');
} finally {
loadingRef.value = false;
}
});
}
async function upload(rawFile: File) {
const inputRefDom = unref(inputRef);
if (inputRefDom) {
// fix can't select the same excel
inputRefDom.value = '';
}
await readerData(rawFile);
}
/**
* @description: 触发选择文件管理器
*/
function handleInputClick(e: Event) {
const files = e && (e.target as HTMLInputElement).files;
const rawFile = files && files[0]; // only setting files[0]
if (!rawFile) return;
upload(rawFile);
}
/**
* @description: 点击上传按钮
*/
function handleUpload() {
const inputRefDom = unref(inputRef);
inputRefDom && inputRefDom.click();
}
return { handleUpload, handleInputClick, inputRef };
},
});
</script>
4、在当前文件的ts中重命名
import { createAsyncComponent } from '/@/utils/factory/createAsyncComponent';
export const ZkImpExcel = createAsyncComponent(() => import('./src/ZkImportExcel.vue'));
export * from './src/types';
export { jsonToSheetXlsx, aoaToSheetXlsx } from './src/Export2Excel';
6、在vue页面调用ZkImpExcel:为ts中const的名称
<ZkImpExcel @success="loadDataSuccess">
<a-button type="primary">导入</a-button>
</ZkImpExcel>
// js导入
function loadDataSuccess(excelData) {
if (excelData.get('file')) {
importExcel(excelData.get('file'));
}
}
|