微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/react/303881.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐