一、上传
<template>
<div class="package-upload container-s-flex">
<el-upload
:http-request="fileUpload"
:on-remove="fileMove"
:on-change="uploadChange"
:before-upload="beforeUpload"
:file-list="files"
:multiple="!isAnnexToServer"
>
<el-button icon="el-icon-upload2" size="small" type="primary">上传文件</el-button>
<span class="upload-info">需使用模板导入,如无模板请点击右侧下载。</span>
<template #tip>
<p class="el-upload__tip" v-show="!files.length">
{{errorTips}}
</p>
</template>
</el-upload>
</div>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs } from "vue";
export default defineComponent({
name:"Upload",
props: {
isAnnexToServer: {
type: Boolean,
default: true,
},
},
emits: ['excelToServer', 'annexToServer'],
setup(prop:any, context:any) {
const state = reactive<any>({
files: [],
errorTips:''
})
function fileUpload(res: any) {
let fd:any = new FormData();
fd.append("file", res.file);
fd.append('fileFolder', '');
//父组件拿到参数调用业务接口
if(prop.isAnnexToServer){
context.emit('excelToServer', fd, res.file);
}else{
context.emit('annexToServer', fd, res);
}
}
function beforeUpload(file: any) {
let suffix = file.name.substring(file.name.lastIndexOf(".") + 1);
const isXls = ['xls', 'xlsx', 'doc', 'docx', 'pdf'].includes(suffix);
if (!isXls) {
state.errorTips = '文件格式不符,请按照要求调整后重新上传';
return false;
}
if (file.size > 30 * 1024 * 1024) {
state.errorTips = '文件大小不应超过30M,请重新上传';
return false;
}
state.errorTips = '';
}
function fileMove() {
state.files = [];
state.errorTips = '';
context.emit('fileMove');
}
function uploadChange(file:any, fileList:any) {
if (prop.isAnnexToServer && fileList.length > 0) {
state.files = [fileList[fileList.length - 1]];
}
}
return {
...toRefs(state),
fileUpload,
beforeUpload,
fileMove,
uploadChange
}
}
})
</script>
二、下载
state.isDownloading = true;
//调取业务接口
downloadTemplate().then((res:any) => {
if (res) {
const a = document.createElement('a');
const url = window.URL.createObjectURL(new Blob([res]));
a.href = url;
a.download = "模板.xls";
a.click();
window.URL.revokeObjectURL(url);
state.isDownloading = false;
}else{
ElMessage.error('下载失败');
state.isDownloading = false;
}
}).catch(() =>{
state.isDownloading = false;
})