ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

【antd】Upload上传组件封装

2022-03-02 12:02:39  阅读:400  来源: 互联网

标签:info 封装 Upload file props antd message 上传 response


这里笔者用的是react+antd

原生antd的写法

const props = {
  name: 'file',
  // 接受的文件类型
  accept: '.xls,.xlsx',
  // 上传的地址
  action: 'url',
  // 是否展示上传的文件
  showUploadList:false,
  // 上传的参数
  data: {
    // token: Cookies.get("token"),
    // uid: Cookies.get('uid')
  },
  withCredentials: true,
  // 设置上传的请求头部,IE10 以上有效
  headers: {
    // authorization: 'authorization-text',
    // "Content-Type": "multipart/form-data"
  },
  onChange(info) {
    if (info.file.status !== 'uploading') {
      message.loading("正在导入中,请稍后");
    }
    if (info.file.status === 'done') {
      if (info.file.response.statusCode !== 200) {
        setTimeout(() => {
          message.destroy();
          message.error(info.file.response.message);
        });
      } else {
        // 上传成功后的服务
      }
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} file upload failed.`);
    }
  },
};
<Upload {...props} >
  	<Button type={"primary"}>导入</Button>
</Upload>

封装后

配置

import React, { Component } from 'react';
import {Button,Upload,message,} from 'antd';
import PropTypes from 'prop-types';

class ImportExportExcel extends Component {
  constructor(props) {
    super(props);
    // 模板下载事件
    this.jumpTo = this.jumpTo.bind(this);
    // 表格导出事件
    this.exportExcel = this.exportExcel.bind(this);
    // 表格上传事件
    this.uploadProps.onChange = this.uploadProps.onChange.bind(this);
  }
  // 模板下载
  jumpTo() {
    window.open(this.props.templateHref);
  }
  // 上传参数
  uploadProps = {
    // 发到后台的文件参数名
    name: 'file',
    // 接受的文件类型
    accept: '.xls,.xlsx',
    // 上传的地址
    action: this.props.url,
    // 是否展示上传的文件
    showUploadList:false,
    // 上传的参数
    data: {
      // token: Cookies.get("token"),
      // uid: Cookies.get('uid')
    },
    withCredentials: true,
    // 设置上传的请求头部,IE10 以上有效
    headers: {
      // authorization: 'authorization-text',
      // "Content-Type": "multipart/form-data"
    },
    // 上传文件前的钩子函数
    beforeUpload() {
      message.loading('正在导入中...');
      return true;
    },
    // 上传文件改变时的状态
    onChange(info) {
      if (info.file.status !== 'uploading') {
		
      }
      if (info.file.status === 'done') {
        if (info.file.response.statusCode !== 200) {
          setTimeout(() => {
            message.destroy();
            message.error(info.file.response.message);
          });
        } else {
          console.log(info.file.response);
          this.props.importSuccessCallback && this.props.importSuccessCallback(info.file.response);
          setTimeout(() => {
            // message.destroy();
            if(info.file.response.message===''){
              message.destroy();
              message.success('导入成功');
            }else{
              message.warn(info.file.response.message);
            }

          });
        }
      } else if (info.file.status === 'error') {
        setTimeout(() => {
          message.destroy();
          message.error('导入失败');
        });
      }
    },
  }

  // 导出Excel表格
  exportExcel() {
    const url = this.props.url ;
    window.open(url);
  }

  render() {
    const uploadProps = this.uploadProps;
    return [
      <Upload key='importExcel' {...uploadProps}  >
        <Button type="primary">{this.props.text}</Button>
      </Upload>
    ]
  }
}

// 定义参数类型
ImportExportExcel.propTypes = {
  // 模板下载地址
  templateHref: PropTypes.string.isRequired,
  // 上传地址
  url: PropTypes.string.isRequired,
  // 导入成功后的回调
  importSuccessCallback: PropTypes.func
};

export default ImportExportExcel;

使用

可以自定义传入按钮名称、上传地址、模板文件、成功回调函数

<ImportExportExcel
    text={"导入xxxExcel"}
    templateHref={"/static/excel/excel_template.xlsx"}
    url={commonUtil.getRootPath()+"/datasource/importExcel1?datasourceId="+currRecord.id}
    importSuccessCallback={
      (res) => {
        if(res.statusCode===200){
          // 成功后的回调
      }
    }
  />

Java后台接收

@PostMapping("/importExcel1")
public JsonResult importExcel1(@RequestParam(value = "file") MultipartFile file,@RequestParam(value="datasourceId") String datasourceId){
	Workbook workbook = WorkbookFactory.create(inputStream);
    int sheetsNum = workbook.getNumberOfSheets();
    ...
}

标签:info,封装,Upload,file,props,antd,message,上传,response
来源: https://blog.csdn.net/qq_37162090/article/details/123226043

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有