使用antd的Upload组件实现文件上传下载

1,777 阅读1分钟

​实现文件上传下载

本项目使用antd pro,umi request,antd中的upload组件显示上传,删除,下载文件等功能,目的在于可以满足开发时关于文件的一些需求提升开发效率。

​文件夹目录

1.将antd中的Upload组件引入项目

<Upload {...uploadProps} fileList={DownloadFile} getValueFromEvent={normFile}>
  <Button icon={<UploadOutlined />}>上传文件</Button>
</Upload>

2.封装操作上传文件class

import { message } from 'antd';
import request from '@/utils/request';

export class FileFunc {
  URL: string; // 用户传入的路由
  Token: string; // 用户传入的token
  Role: any; // 用户的一下基本信息
  isChangeList?: boolean;
  constructor(URL: string, Token: string, Role: any, isChangeList: boolean) {
    this.URL = URL;
    this.Token = Token;
    this.Role = Role;
    this.isChangeList = isChangeList;
  }
  // 删除指定报告Method
  removeFile = async (File: any) => {
    const REMOVE_FILE: any = await request.get(this.URL, {
      params: { delete_id: File.id },
    });
    if (REMOVE_FILE.code === 2000) {
      this.isChangeList = true;
      message.success(REMOVE_FILE.message);
    } else {
      message.error('删除失败');
    }
  };
  // 获取当前用户下的所有上传文档
  getFileInfo = async () => {
    try {
      const RED_ALL_FILE = await request.get(this.URL, {
        params: { user_id: this.Role.id },
      });
      if (RED_ALL_FILE.code === 2000) {
        RED_ALL_FILE.data.forEach((item: any, index: number) => {
          RED_ALL_FILE.data[index]['status'] = 'done';
          RED_ALL_FILE.data[index]['name'] = item.file_name;
        });
        return RED_ALL_FILE.data;
      }
    } catch (error) {
      console.log(error);
    }
  };
  downloadInstitutionSingleFile = async (File: any) => {
    const DOWNLOAD_ALL_FILE: any = await request.get(this.URL, {
      params: { id: File.id },
      responseType: 'blob',
      getResponse: true,
    });
    const hide = message.loading('下载中...', 0);
    try {
      if (DOWNLOAD_ALL_FILE) {
        setTimeout(hide, 500);
        const CD = DOWNLOAD_ALL_FILE.response.headers.get('content-disposition').split(';');
        let CD_TEMP: string = '';
        for (let i = 0; i < CD.length; i += 1) {
          if (!CD[i].indexOf('filename=')) CD_TEMP = CD[i];
        }
        const FILE_EXTENSION = CD_TEMP.split('.')[CD_TEMP.split('.').length - 1];
        let fileName = '未识别的文件名';
        if (File.name) {
          fileName = `${File.name}`;
        } else {
          fileName = `未识别的文件.${FILE_EXTENSION}`;
        }
        this.convertRes2Blob(DOWNLOAD_ALL_FILE.data, fileName);
        message.success('下载成功');
      } else {
        message.error('下载失败');
      }
    } catch (error) {
      console.log(error);
    }
  };
  convertRes2Blob(data: any, filename = '下载内容') {
    const blob = new Blob([data], { type: 'application/octet-stream' });
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
      window.navigator.msSaveBlob(blob, decodeURI(filename));
    } else {
      const blobURL = window.URL.createObjectURL(blob);
      const tempLink = document.createElement('a');
      tempLink.style.display = 'none';
      tempLink.href = blobURL;
      tempLink.setAttribute('download', decodeURI(filename));
      if (typeof tempLink.download === 'undefined') {
        tempLink.setAttribute('target', '_blank');
      }
      document.body.appendChild(tempLink);
      tempLink.click();
      document.body.removeChild(tempLink);
      window.URL.revokeObjectURL(blobURL);
    }
  }
  getMessageSuccess = (notice: string) => {
    message.success(notice);
  };
  getMessageError = (notice: string) => {
    message.error(notice);
  };
}

3.引用定义class

 const filePublicFunc = new FileFunc(
    '你对接的接口',
    '传入的token',
    '用户的信息',
  );

​ **4.配置上传文件属性文件上传按钮属性 ** ​

 // 文件上传按钮属性
  const uploadProps = {
    name: 'file',
    action: '***',
    method: 'POST',
    accept: '.jpeg ,.jpg ,.png,.pdf,.docx,.mp4,.mp3,.xls,.doc,.xlsx',
    headers: { Authorization: `Bearer ${accessToken}` },
    data: { user_id: accountInfo.id },
    disabled: false,
    FileList: DownloadFile,
    showUploadList: {
      //   showPreviewIcon: '预览',
      showDownloadIcon: true,
      showRemoveIcon: false,
      removeIcon: (
        <img
          className="removeIcon"
          src="***"
        />
      ),
    },
    onDownload: (file: any) => {
      filePublicFunc.downloadInstitutionSingleFile(file);
    },
    onRemove: (file: any) => {
      filePublicFunc.removeFile(file);
      if (DownloadFile.length > 1) {
        filePublicFunc.removeFile(file);
      } else {
        message.warning('至少保留一条');
      }
    },
    onChange: (info: any) => {
      if (info.fileList.length >= 1) {
        setDownloadFile(info.fileList);
      }
      try {
        if (info.file.status === 'done') {
          if (info.file.response.code === 2000) {
            filePublicFunc.getFileInfo().then((res: any) => {
              console.log('上传成功后的文件',res)
              message.success('上传成功');
            });
          } else {
            message.error('上传失败');
            // setDownloadFile(info.fileList);
          }
        }
        if (info.file.status === 'error') {
          message.error('上传失败');
          // setDownloadFile(info.fileList);
        }
        if (info.file.status === 'uploading') {
            console.log('uploading',info.file.status)
        }
      } catch (error) {
        console.log(error);
      }
    },
  };

​这样一个简单的上传下载删除项目组件就完成啦!!!

npm包:npm-aupload-greninja

本项目github地址:GitHub - Sun-Lampyridae/npm-antd-upload: 使用antd upload组件