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

前端之家收集整理的这篇文章主要介绍了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://www.f2er.com/react/303881.html

猜你在找的React相关文章