Bootstrap

摘录: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;
};

;