实现导入导出

//service.js
import { APIS } from '../core/common/config'
import AjaxRequest from '../core/common/ajaxRequest.js'

// const service = "http://192.168.110.2:25002/";
const service = APIS.domain
function formalData(data) {
  let dataStr = '' //数据拼接字符串
  Object.keys(data).forEach((key) => {
    dataStr += key + '=' + data[key] + '&'
  })
  if (dataStr !== '') {
    dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'))
  }
  return dataStr
}

/**
 * @description: 下载模板
 */
export function exportModules() {
  window.open(`${service}order/center/downloadForecastsTemplate`)
}

/**
 * @description: 上传文件
 */

export function importTemplate(data, callback) {
  var req = new XMLHttpRequest()
  console.log(data.get(`file`))
  // req.open("POST", `${service}order/center/importTemplate`, true);
  // /order/center/importForecastsExcel
  req.open('POST', `${service}order/center/importForecastsExcel`, true)
  // req.setRequestHeader("Content-Type", "multipart/form-data"); 设置请求头需要自己指定boundary
  req.setRequestHeader('corTicket', localStorage.getItem('cor-ticket'))
  req.onreadystatechange = function () {
    if (req.readyState === 4) {
      if (req.status >= 200 && req.status < 300) {
        callback(req.response)
      } else {
        toastr.error(`操作失败`)
      }
    }
  }
  req.send(data)
}

/**
 * @description 导出列表
 */
export function exportSalesForecasts(data, callback) {
  let params = formalData(data)
  // console.log(`order/center/exportSalesForecasts?${params}`,'---------43536')
  window.open(`${service}order/center/exportSalesForecasts?${params}`)
}

//使用导入导出list.js
    const exportProps = {
      visible: this.state.exportVisible,
      cancel: () => this.setState({ exportVisible: false }),
      getTableData: (body) => { this.getTableData(body) }
    }
     {exportVisible && <Export {...exportProps}></Export>}



//导入导出Export.js
import React, { Component } from "react";
import { Modal } from "antd";
import { exportModules, importTemplate } from "./service";
module.exports = class exports extends Component {
  state = {
    filelName: "",
    flag: true, // 用于判断ajax请求重复发送

  };
  cancel = () => {
    const { cancel } = this.props;
    cancel();
  };

  downloadTemplate = () => {
    exportModules();
  };

  importTemplates = () => {
    this.fileRef.click();
  };
  componentDidMount() {
    //   componentDidMount 获取不到ref
    //  组件挂载完成 但是modal框没有显示 导致获取不到元素
    // console.log(document.getElementById("fileImport")); // null
    // console.log(this.fileRef); // undefind
    this.fileRef.addEventListener("change", this.alterFile);
  }
  alterFile = (e) => {
    let files = e.target.files && e.target.files[0];
    this.setState({
      filelName: files.name,
    });
  };
  componentWillUnmount() {
    this.fileRef.removeEventListener("change", this.alterFile);
  }
  submitFn = () => {
    const { flag } = this.state;
    if (!flag) return;
    const file = this.fileRef.files && this.fileRef.files[0]; // 文件流的数据
    let formData = new FormData();
    formData.append("file", file);
    this.state.flag = false;
    importTemplate(formData, (body) => {
      body = JSON.parse(body);
      this.state.flag = true;
      // body && body.status
      if (body.data) {
        this.props.cancel();
        toastr.success('操作成功');
        this.props.getTableData(body.data)
      } else {
        if (body.message.includes('<br/>')) {
          let res = body.message.split('<br/>').reverse()
          res.shift()
          res.forEach(x => toastr.error(x))
          return
        }
        toastr.error(body.message);
      }
    });
  };
  render() {
    const { visible } = this.props;
    const { filelName } = this.state;
    return (
      <Modal visible={visible} onCancel={this.cancel} onOk={this.submitFn}>
        <div className="export-modules">
          <div>第一步: 下载模板</div>
          <div>
            <button
              type="button"
              className="btn btn-primary"
              onClick={this.downloadTemplate}
            >
              下载模板
            </button>
          </div>
          <div>第二步: 上传文件</div>
          <div>
            <button
              type="button"
              className="btn btn-success"
              onClick={this.importTemplates}
            >
              <input
                type="file"
                ref={(e) => (this.fileRef = e)}
                style={{ display: "none" }}
              />
              上传文件
            </button>
            {filelName && (
              <div className="fileName">
                文件名:<span>{filelName}</span>
              </div>
            )}
          </div>
        </div>
      </Modal>
    );
  }
};

 

//手写封装过滤
import React, { Component } from "react";
import { Form, Select, Input } from "antd";
const FormItem = Form.Item;
const Option = Select.Option;
module.exports = class Filters extends Component {
  state = {
    statusArray: [],
    demandCollectStatusArray: [],
    dateKey: 0,
    filters: this.props.filters || [],
    selectVal: ""
  };

  getSelectValue = (body, fields) => {
    let obj = {};
    obj[fields] = body.data;
    this.setState(obj);
  };

  getValue = () => {
    const { searchObj } = this.state;
    return searchObj;
  };
  // 重置查询
  resetSearch = () => {
    const { reset } = this.props;
    this.setState({
      dateKey: Date.now(),
    });
    reset();
  };
  // 查询确定
  handleSearchSubmit = () => {
    const { submit } = this.props;
    submit();
  };
  handleChange = (e, fileds,sKey,value) => {
    const { handleChange: handleChangeProps } = this.props;
    handleChangeProps(e, fileds,sKey,value);
  };
  render() {
    const { dateKey, filters, selectVal } = this.state;
    const { searchObj } = this.props;
    return (
      <div className="saleForecast">
        <Form>
          <div className="filter-title">
            <button className="btn btn-cancle" onClick={this.resetSearch}>
              重置
            </button>
            <button
              className="btn btn-danger"
              onClick={this.handleSearchSubmit}
            >
              确定
            </button>
          </div>
          {filters.map((x) => {
            return (
              <FormItem label={x.title}>
                {
                  !x.selectType ? <Input
                    value={searchObj[x.name]}
                    placeholder={x.text}
                    onChange={(e) => {
                      this.handleChange(e.target.value, x.name);
                    }}
                  /> :
                    <Select
                      value={searchObj[x.fields]}
                      placeholder={x.text}
                      onChange={(e) => {
                        let sKey = ''
                        sKey = x.optionArray.reduce((pre, cur) => pre === cur.sValue ? cur.sKey : pre, e)
                        this.handleChange(e, x.name, sKey,x.fields);
                      }}
                    >
                      {
                        x.optionArray && x.optionArray.map(x => {
                          return (
                            <Option value={x.sValue} key={x.id}>
                              {x.sValue}
                            </Option>
                          )
                        })
                      }
                    </Select>
                }
              </FormItem>
            );
          })}
        </Form>
      </div>
    );
  }
};

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值