作者:仲颖凯翰奕颖 | 来源:互联网 | 2023-07-25 15:43
1.html
upload
class="btn-upload"
:action="''"
:http-request="uploadBtn"
:on-error="uploadError"
:show-file-list="false"
accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
>
button
type="primary"
size="small"
round
icon="el-icon-upload2">
上传
2.js
import XLSX from 'xlsx';
// 按钮-上传
uploadBtn(uploadData: any) {
const rABS = true;
const f = uploadData.file;
const reader = new FileReader();
let jsonArr = [];
reader.onload = (e: any) => {
let data: any = e.target.result;
if (!rABS) data = new Uint8Array(data);
const workbook = XLSX.read(data, {
type: rABS ? 'binary' : 'array'
});
const first_worksheet = workbook.Sheets[workbook.SheetNames[0]]; // 拿第一个sheet的内容
jsOnArr= XLSX.utils.sheet_to_json(first_worksheet, {header:1}); // 转成array
const uploadFileCOntentList= jsonArr.filter((item: any) => {
if (item.length > 0) {
return item;
}
})
// 读取到文件名称、内容行数,提示用户
this.$confirm(`将上传【${uploadData.file.name}】,共${uploadFileContentList.length}行, 是否继续?`, '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
this.uploadRequest(uploadData); // 调接口
}).catch(() => {
this.$message({
type: 'info',
message: '已取消'
});
});
};
if (rABS) reader.readAsBinaryString(f); else reader.readAsArrayBuffer(f);
}
// 接口:上传
async uploadRequest(data: any) {
this.uploadAssignLoading = Loading.service({
fullscreen: true,
text: '上传中,请耐心等待...'
});
let params = new FormData();
params.append('file', data.file); // 添加参数
await network.xxxApi.upload(params).catch(() => {
this.$nextTick(() => {
this.uploadAssignLoading.close();
});
this.$message({
type: 'info',
message: '网络异常,请重试',
});
});
this.uploadAssignLoading.close(); // 关loading
this.$message({
type: 'success',
message: '上传成功'
});
}
// 上传分配: 失败
uploadAssignError(data: any) {
this.uploadAssignLoading.close();
this.$message({
type: 'info',
message: '异常,请重试',
});
}