摘录:vue上传功能实现

axios代码

export async function uploadFile(data: Record<string, any>): Promise<any> {
  return request('/di-org/region/orgChart/import', {
    method: 'POST',
    data,
    responseType: 'blob',
    timeout: 60 * 1000,
  });
}

上传代码html

<a-form
      ref="formRef"
      :rules="rules"
      :model="formState"
      name="basic"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 17 }"
      autocomplete="off"
    >
      <a-form-item ref="file" name="file" label="Import File">
        <a-upload
          v-model:file="formState.file"
          name="file"
          accept=".xlsx"
          :before-upload="file => beforeUpload(file)"
          :maxCount="1"
        >
          <a-button>
            <upload-outlined></upload-outlined>
            Click to Upload
          </a-button>
        </a-upload>
      </a-form-item>
    </a-form>

上传代码ts

// upload前校验
const beforeUpload = async (file: File) => {
  const typeValid =
    ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'].filter(
      (el: any) => file.type.indexOf(el) > -1,
    ).length > 0;
  const sizeValid = file.size / 1024 / 1024 <= 5;
  const isValid = typeValid && sizeValid;
  if (!typeValid) {
    message.error('文件类型有误');
  }
  if (!sizeValid) {
    message.error('文件尺寸不能大于5M');
  }
  if (isValid) {
    formState.file = file;
    // getBase64(file, (base64Url: string) => {
    //   state.imageUrl = base64Url;
    // });
  }
  return false;
};

// 数据提交
const customRequest = async () => {
  const formData = new FormData();
  formData.append('id', props.id);
  formData.append('file', formState.file);
  return new Promise(resolve => {
    uploadFile(formData)
      .then(data => {
        const blob = new Blob([data]);
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = `ImportResult.xlsx`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        resolve(data);
      })
      .catch(error => {
        console.log(error);
        resolve(null);
      });
  });
};


const handleSave = async () => {
  let data: any = await customRequest();
  if (data) {
    // DO SOMETHING
  }
  state.submitLoading = false;
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值