上传下载功能

一、上传

<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;
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值