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;
相關文章
相關標籤/搜索