React 同步上传excle,并下载结果

import fetch from 'ascm-comp/lib-fetch/index';

const React = require('mui/reactjs/react');
const Fusion = require('mui/fusion/index');

const { Button } = Fusion;

require('./index.less');

class UploadModal extends React.Component {

  static propTypes = {
    action: React.PropTypes.string,
    resultFileName: React.PropTypes.string,
    name: React.PropTypes.string,
  }

  uploadClick() {
    return () => {
      this.upload.click();
    };
  }

  post() {
    return (e) => {
      const oReq = new XMLHttpRequest();
      oReq.open('POST', this.props.action, true);
      oReq.responseType = 'arraybuffer';
      oReq.withCredentials = true;
      oReq.onload = function () {
        const arrayBuffer = oReq.response; // Note: not oReq.responseText
        if (arrayBuffer) {
          const byteArray = new Uint8Array(arrayBuffer);
          const aLink = document.createElement('a');
          const blob = new Blob([byteArray], { type: 'application/vnd.ms-excel' });
          let fileName = this.props.resultFileName ||'result.xlsx';
          try {
            const disposition = oReq.getResponseHeader('Content-Disposition') || '';
            fileName = disposition.split('filename=').length > 1 ? disposition.split('filename=')[1] : 'result.xlsx';
          } catch (err) {
            console.error(err);
          }
          aLink.download = fileName;
          aLink.href = URL.createObjectURL(blob);
          aLink.target = '_blank';
          document.body.appendChild(aLink);
          aLink.click();
        }
      };
      const form = new FormData();
      form.append(this.props.name||'file', e.target.files[0]);
      form.append('_scm_token_', window._scm_token_);
      oReq.send(form);
    };
  }

  render() {

    return (
      <span>
        <Button onClick={this.uploadClick()}>{this.props.children}</Button>
        <input
          type="file" ref={(c) => { this.upload = c; }}
          onChange={this.post()}
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;"
          style={{ display: 'none' }}
        />
      </span>
    );
  }
}

module.exports = UploadModal;

转载于:https://my.oschina.net/u/867090/blog/912822

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值