1.定义数据、导入对话框代码
<el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
<el-upload
ref="uploadRef"
:limit="1"
accept=".pdf,.xlsx"
:headers="upload.headers"
:action="upload.url "
:disabled="upload.isUploading"
:on-progress="handleFileUploadProgress"
:on-success="handleFileSuccess"
:auto-upload="false"
drag
>
<el-icon class="el-icon--upload"><upload-filled /></el-icon>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<template #tip>
<div class="el-upload__tip text-center">
<span>仅允许导入pdf、xlsx格式文件。</span>
</div>
</template>
</el-upload>
<template #footer>
<div class="dialog-footer">
<el-button type="primary" @click="submitFileForm">确 定</el-button>
<el-button @click="upload.open = false">取 消</el-button>
</div>
</template>
</el-dialog>
const upload = reactive({
// 是否显示弹出层(用户导入)
open: false,
// 弹出层标题(用户导入)
title: "",
// 是否禁用上传
isUploading: false,
// 是否更新已经存在的用户数据
// updateSupport: 0,
// 设置上传的请求头部
headers: { Authorization: "Bearer " + getToken() },
// 上传的地址
url: import.meta.env.VITE_APP_BASE_API + "/common/upload"
});
2.解析代码需要先按照解析pdf和xlsx文件的依赖
安装pdfjs最好加上版本号,高版本的会出现引入报错问题(我使用vue3的时候会)
npm install pdfjs-dist@2.2.228
npm install xlsx
引入pdf和xlsx依赖
import * as XLSX from 'xlsx';
import pdfjsLib from 'pdfjs-dist/build/pdf.js'
// 设置全局的 Worker 脚本路径
pdfjsLib.GlobalWorkerOptions.workerSrc = '/node_modules/pdfjs-dist/build/pdf.worker.js';
// 使用pdf.js解析PDF文件的方法
const parsePDF = async (file) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = async () => {
try {
const arrayBuffer = reader.result;
// 使用pdf.js解析PDF文件
const loadingTask = pdfjsLib.getDocument(arrayBuffer);
const pdf = await loadingTask.promise;
// 获取pdf的页数
const numPages = pdf.numPages;
// 提取PDF文本内容
let pageContent=[];
for (let i = 1; i <= numPages; i++) {
const page = await pdf.getPage(i);
const pageText = await page.getTextContent();
console.log(pageText);
pageContent=pageContent.concat(pageText.items)
//可以在这里处理获取到的数据
}
resolve(pageContent);
} catch (error) {
reject(error);
}
};
// 创建一个Blob对象并传递给readAsArrayBuffer方法
reader.readAsArrayBuffer(file.raw);
});
};
// 解析xlsx文件的方法
const parseXLSX = async (file) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
try {
const arrayBuffer = reader.result;
const uint8Array = new Uint8Array(arrayBuffer);
const workbook = XLSX.read(uint8Array , { type: 'array' });
const sheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[sheetName];
const data = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
resolve(data);
} catch (error) {
reject(error);
}
};
reader.readAsArrayBuffer(file);
});
};
在导入成功函数中使用
const handleFileSuccess = (response, file, fileList) => {
if (file.raw.type === 'application/pdf') {
// 在这里处理上传的PDF文件,可以调用pdf.js解析PDF文件并提取数据
parsePDF(file).then(res => {
console.log(res);
}).catch(error => {
console.error(error);
});
}else if (file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
parseXLSX(file.raw).then(data => {
console.log(data);
// 在这里可以对提取的数据进行进一步处理
}).catch(error => {
console.error(error);
});
}
upload.open = false;
upload.isUploading = false;
proxy.$refs["uploadRef"].handleRemove(file);
proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
getList();
};