文件上传和下载功能

上传下载功能:

用到的 UI 库为 Antdv 组件库

页面层代码:

<div>
                <a-upload
                  name="file"
                  accept=".xls,.xlsx" // 接受上传的文件类型
                  :customRequest="customRequest" // 自定义上传事件,覆盖默认行为
                  :before-upload="beforeUpload" // 上传前的钩子
                  :showUploadList="false" // 是否展示 uploadList 
                >
                  <a-icon type="upload" :class="['icon-color', textFontSizeMiddle]" /> // 上传的 icon 图标 
                </a-upload>
                <a-icon
                  type="download"
                  @click="download" // 下载的图标和方法
                  :class="['icon-color', textFontSizeMiddle]"
                />
              </div>

用到的方法:

	beforeUpload(file) {
      console.log(file, 'fff');
      if (file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
        this.$message.warning('上传的文件类型必须是.xls,.xlsx');
        return false;
      }
    },
    customRequest(file) {
      this.$message.loading({ content: '正在上传...', key: this.key, duration: 0 });
      console.log(file, 'file');
      const formData = new FormData();
      formData.append('file', file.file);
      // 后端提供的接口
      uploadFile(formData).then((res) => {
        console.log(res);
        if (res.status == 200) {
          this.$message.success({ content: res.message, key: this.key, duration: 2 });
          window.location.reload();
        } else {
          this.$message.success({ content: res.message, key: this.key, duration: 2 });
        }
      });
    },
    // 下载方法
    download() {
      // 后端提供的接口
      downLoad().then((res) => {
        console.log(res.data);
        const blob = new Blob([res.data]);
        // 封装一个保存的插件 可以抽离到utils中
        saveFile(blob, '数据更新模板.xlsx');
      });
    },

utils中封装的保存方法


export function saveFile(data, name) {
  try {
    const blobUrl = window.URL.createObjectURL(data);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.download = name;
    a.href = blobUrl;
    a.click();
  } catch (e) {
    alert('保存文件出错');
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值